The try...except statement is used to handle errors and prevent a program from crashing. When an error occurs inside the try block, Python executes the except block.
Basic Try Except
Syntax
try:
# code that may cause an error
except:
# code to handle the error
Example
try:
print(10 / 0)
except:
print("An error occurred")
Output:
An error occurred
Catch Specific Exceptions
Example
try:
number = int("abc")
except ValueError:
print("Invalid number")
Output:
Invalid number
Multiple Except Blocks
Example
try:
number = int("abc")
print(10 / 0)
except ValueError:
print("Value Error")
except ZeroDivisionError:
print("Division by zero")
Output:
Value Error
Using Exception as a Variable
Example
try:
print(10 / 0)
except Exception as error:
print(error)
Output:
division by zero
Try Except Else
The else block runs if no exception occurs.
Example
try:
print(10 / 2)
except ZeroDivisionError:
print("Error")
else:
print("Operation successful")
Output:
5.0
Operation successful
Try Except Finally
The finally block always executes, whether an exception occurs or not.
Example
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution completed")
Output:
Cannot divide by zero
Execution completed
Complete Example
Example
try:
num = int(input("Enter a number: "))
result = 100 / num
except ValueError:
print("Please enter a valid number")
except ZeroDivisionError:
print("Number cannot be zero")
else:
print("Result:", result)
finally:
print("Program ended")
Summary
trycontains code that may cause an error.excepthandles errors.- Multiple
exceptblocks can handle different exceptions. Exception as errorprovides the actual error message.elseexecutes when no exception occurs.finallyalways executes.- Exception handling makes programs more reliable and user-friendly.