Exception handling in Python
Exception handling
in Python is a mechanism to deal with runtime errors or exceptional situations
that may occur during the execution of a program.
It allows you to
catch and handle errors gracefully, preventing the program from terminating
abruptly.
The key components
of exception handling in Python are the `try`, `except`, `else`, and `finally`
blocks.
The basic structure of exception handling in Python:
try:
# Code that might raise an exception
# ...
result = 10 / 0 # Example of a potential exception (division
by zero)
# ...
except SomeSpecificException as e:
# Handle a specific type of exception
print(f"Caught an exception:
{e}")
except AnotherSpecificException as e:
# Handle another specific type of exception
print(f"Caught another exception:
{e}")
except Exception as e:
# Handle any other exceptions
print(f"Caught a generic exception:
{e}")
else:
# Code to be executed if no exception
occurs in the try block
print("No exception occurred.")
finally:
# Code that will be executed no matter
what, whether an exception occurred or not
print("This block is always
executed.")
Description:
- The `try` block
contains the code that might raise an exception.
- The `except`
block catches and handles exceptions.
- You can have
multiple `except` blocks to handle different types of exceptions.
- The `else` block
contains code that will be executed if no exception occurs in the `try` block.
- The `finally`
block contains code that will be executed no matter what, whether an exception
occurred or not. It is often used for cleanup operations.
Example :
try:
num1 = int(input("Enter a number:
"))
num2 = int(input("Enter another
number: "))
result = num1 / num2
print(f"Result: {result}")
except ValueError:
print("Invalid input. Please enter a
valid number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Division successful.")
finally:
print("End of the program.")
```
In this example, if the user enters invalid input or attempts to divide by zero, the program will catch and handle the respective exceptions, providing a more user-friendly experience.
=====================================================================
0 Comments