Python Exception Handling: Try‑Except, Else, Finally, and Raising Exceptions
This article explains Python's exception handling mechanisms, covering the basic try‑except syntax, handling specific error types, using else and finally blocks, raising custom exceptions, and demonstrates practical examples such as user input validation and error propagation across functions.
Python provides a structured way to handle runtime errors using the try , except , else , and finally statements. The simplest form catches any exception:
try:
# code that may raise an exception
except:
# handle the errorSpecific exception types can be targeted to provide tailored responses:
try:
num = int(input("Enter an integer: "))
except ValueError:
print("Please enter a valid number!")
except ZeroDivisionError:
print("Math error")A more comprehensive example asks the user for an integer, divides 8 by that number, and handles both ZeroDivisionError and ValueError :
while True:
try:
# Prompt user for an integer
num = int(input("Enter an integer: "))
result = 8 / num
print(result)
except ZeroDivisionError:
print("Math error")
except ValueError:
print("Please enter a number")Exceptions propagate up the call stack. If a function raises an error and it is not caught locally, the caller can handle it:
def demo1():
return int(input("Enter integer: "))
def demo2():
return demo1()
try:
print(demo2())
except Exception as e:
print(f"Program encountered an error: {e}")Custom exceptions can be raised deliberately using the raise statement. The following function validates a password length and raises an exception if it is too short:
def input_password():
pwd = input("Enter password: ")
if len(pwd) >= 8:
return pwd
else:
print("Raising exception!")
ex = Exception("Password length insufficient!")
raise ex
try:
print(input_password())
except Exception as e:
print(e)The complete syntax for exception handling combines all parts:
try:
# code that may raise an exception
except SpecificError1:
# handle error type 1
except (SpecificError2, SpecificError3):
# handle error types 2 and 3
except Exception as e:
# handle any other exception
print(e)
else:
# executed if no exception occurs
pass
finally:
# always executed
print("This runs regardless of exceptions")These examples illustrate the fundamental techniques for managing errors in Python programs.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.