Python : Exception Handling
Exception handling is an important part of writing robust and reliable code in Python.
What is Exception in Python?
Exceptions are runtime errors that occur when your code encounters an unexpected situation.
Take an example, trying to divide a number by zero will raise a
ZeroDivisionError. In Python, we can use try-except blocks to handle exceptions.
Syntax of a try-except block:
try: # code that may raise an exception except ExceptionType: # code to handle the exception
try block contains the code that may raise an exception, and the
except block contains the code to handle the exception. The
ExceptionType is the type of exception that the
except block will handle. You can specify multiple
except blocks to handle different types of exceptions.
Handling Exceptions in Python:
There are several ways to handle exceptions in Python:
Using try-except blocks:
We can use
try-exceptblocks to handle exceptions in our code. This is the most common way to handle exceptions in Python.
Using finally block:
We can use the
finallyblock to execute code that should be run regardless of whether an exception occurred or not.
We can raise
exceptionsourselves using the
raisekeyword. This is useful when we want to indicate that an error occurred in our code.
Using the assert statement:
assertstatement is used to check if a condition is true, and if it is not true, it raises an
def divide(x, y): try: result = x / y except ZeroDivisionError: print("Error: division by zero") else: print("Result is", result) finally: print("Execution complete")
In the above example, we have defined a function called divide that takes two arguments
y. We use a
try-except block to handle the
ZeroDivisionError that can occur when
y is zero. If no exception occurs, we print the result, and if an exception occurs, we print an error message. The finally block is used to execute code that should be run regardless of whether an exception occurred or not.