Error Handling in Python
1. What are Exceptions?
An exception is an error that occurs during program execution. When an
exception is raised, it disrupts the normal flow of the program.
Common exceptions include ZeroDivisionError, ValueError, TypeError, and
FileNotFoundError.
Example of an Exception:
print() # Raises ZeroDivisionError
2. Handling Exceptions with try-except
Use a try-except block to catch exceptions and prevent program crashes.
Syntax:
try:
# Code that might raise an exception
risky_code()
except ExceptionType:
# Code to handle the exception
handle_error()
Example:
try:
result =
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
, csharp
Cannot divide by zero!
3. Handling Multiple Exceptions
You can handle different types of exceptions with separate except blocks.
Example:
try:
value = int(input("Enter a number: "))
print(10 / value)
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
4. Using else with try-except
The else block runs if no exception occurs in the try block.
Example:
try:
value = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print(f"You entered: {value}")
5. Using finally
The finally block executes regardless of whether an exception occurred or
not. It's typically used for cleanup actions.
1. What are Exceptions?
An exception is an error that occurs during program execution. When an
exception is raised, it disrupts the normal flow of the program.
Common exceptions include ZeroDivisionError, ValueError, TypeError, and
FileNotFoundError.
Example of an Exception:
print() # Raises ZeroDivisionError
2. Handling Exceptions with try-except
Use a try-except block to catch exceptions and prevent program crashes.
Syntax:
try:
# Code that might raise an exception
risky_code()
except ExceptionType:
# Code to handle the exception
handle_error()
Example:
try:
result =
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
, csharp
Cannot divide by zero!
3. Handling Multiple Exceptions
You can handle different types of exceptions with separate except blocks.
Example:
try:
value = int(input("Enter a number: "))
print(10 / value)
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
4. Using else with try-except
The else block runs if no exception occurs in the try block.
Example:
try:
value = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print(f"You entered: {value}")
5. Using finally
The finally block executes regardless of whether an exception occurred or
not. It's typically used for cleanup actions.