Exceptions in Python
Python provides mechanisms for handling exceptions, similar to other programming languages like Java.
What is an exception? It's an unexpected event that disrupts or alters the program's normal flow. For example, dividing a number by zero. Exceptions are used to manage these anomalous events.
To handle exceptions in Python, you use the TRY / EXCEPT statements.
An Example of an Exception in Python
In this example, I've intentionally created a scenario that causes an error.
In the first two lines, I assign the values zero and five to the variables A and B, respectively.
In the third line, I attempt to display the result of dividing A by B.
a=0
b=0
print(b/a)
Division by zero is not possible.
Therefore, running this code will produce an error.
ERROR
Handling the Error with an Exception
To prevent the error from appearing, I can anticipate this scenario in my code and handle it using an exception.
I place the TRY statement before the PRINT statement. This instructs the program to attempt the operation.
try:
print(b/a)
except ZeroDivisionError:
print("division by zero is not possible")
After PRINT, I add an EXCEPT clause followed by the specific error I want to catch (ZeroDivisionError) and the alternative code to execute if this error occurs.
Program Execution Result
When executed, the program no longer displays an error message.
- If the division B/A is possible, the program displays the result of the division (quotient). For instance, if B=6 and A=2, the program shows 3 as the result:
3
- If the division B/A is not possible because A is zero (A=0), regardless of B's value, the program shows the message "division by zero is not possible".
division by zero is not possible
This way, I've caught an error and handled it using an exception.
Note: Each exception only handles one specific type of error. In the previous example, I handled one type of error (division by zero). If another type of error occurs (e.g., one of the values is alphanumeric), the program will still return an error.
Types of Exceptions in Python
In Python, there are two types of exceptions:
- Handled exceptions
- Unhandled exceptions