Python exception handling:
Exception handling in Python allows you to deal with errors and unexpected situations gracefully. The primary keywords for exception handling are try
, except
, else
, and finally
.
Basic Exception Handling:
Basic exception handling in Python involves using the try
and except
blocks to catch and handle exceptions.
Here’s a simple example:
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code to handle the specific exception
print(“Cannot divide by zero!”)
In this example:
- Within the try block resides the code that has the potential to raise an exception.
- The
except
block catches the specific exception (ZeroDivisionError
in this case) and executes the code inside the block. - If an exception occurs in the
try
block, the control transfers to the matchingexcept
block.
Various types of exceptions can be captured and managed appropriately:
try:
# Code that may raise an exception
result = int(“abc”)
except ValueError:
# Code to handle the specific exception
print(“Invalid conversion to integer!”)
In this example, the except
block catches a ValueError
if the conversion to an integer fails.
Capturing multiple exceptions within a unified except block is also achievable:
try:
# Code that may raise an exception
result = int(“abc”)
except (ValueError, TypeError):
# Code to handle multiple exceptions
print(“Invalid conversion to integer or incorrect type!”)
The except
block is executed only if any of the specified exceptions occur in the corresponding try
block.
These are the fundamental components of basic exception handling in Python. It allows you to gracefully handle errors and prevent your program from crashing when unexpected situations arise.
Handling Multiple Exceptions:
In Python, you can handle multiple exceptions in a single except
block by specifying the exceptions within parentheses. This allows you to provide a common handling routine for different types of exceptions.
Here’s an example:
try:
# Code that may raise exceptions
result = int(“abc”)
result = 10 / 0
except (ValueError, ZeroDivisionError) as e:
# Code to handle multiple exceptions
print(f”An exception occurred: {e}”)
In this example:
- The
try
block contains code that may raise either aValueError
or aZeroDivisionError
. - The
except
block catches both exceptions and prints a generic message along with the exception information.
You can catch as many exceptions as needed within the same except
block, separating them with commas:
try:
# Code that may raise exceptions
result = int(“abc”)
result = 10 / 0
except (ValueError, TypeError) as ve:
# Code to handle ValueError or TypeError
print(f”ValueError or TypeError: {ve}”)
except ZeroDivisionError as zd:
# Code to handle ZeroDivisionError
print(f”ZeroDivisionError: {zd}”)
except Exception as e:
# Code to handle any other exceptions
print(f”An exception occurred: {e}”)
In this example:
- The first
except
block handles bothValueError
andTypeError
. - The second
except
block handlesZeroDivisionError
. - The third
except
block is a generic catch-all for any other exceptions.
Note that the order of except
blocks matters. Python will execute the first block whose exception type matches the raised exception.
Handling multiple exceptions in one block is useful when you want to provide a common response to different types of errors or when you want to minimize redundant code.
Using ‘else’ with ‘try’ Exceptions:
In Python, the else
block in conjunction with try
and except
allows you to specify a block of code that will be executed if no exceptions are raised in the corresponding try
block.
The basic structure is as follows:
try:
# Code that may raise an exception
result = 10 / 2
except ZeroDivisionError:
# Code to handle the specific exception
print(“Cannot divide by zero!”)
else:
#Code to run in the absence of any exceptions
print(f”Result: {result}“)
In this example:
- The
try
block contains code that might raise aZeroDivisionError
. - If a
ZeroDivisionError
occurs, the control transfers to theexcept
block, and the specific exception handling code is executed. - If no exception occurs, the
else
block is executed, and it contains code that runs only when there is no exception.
Here’s another example with multiple exceptions and an else
block:
try:
# Code that may raise exceptions
result = int(“42”)
except (ValueError, TypeError):
# Code to handle multiple exceptions
print(“Invalid conversion to integer or incorrect type!”)
else:
#Code to run if there are no exceptions
print(f”Result: {result}”)
In this case, if a ValueError
or TypeError
occurs, the except
block is executed. If no exception occurs, the else
block is executed.
The else
block is optional, and its code is executed only when no exceptions are raised in the corresponding try
block. It provides a way to separate the code that may raise exceptions from the code that should run only when there are no exceptions.
Using ‘finally’ Exception:
In Python, the finally
block is used in conjunction with try
and except
to specify a block of code that will be executed whether an exception occurs or not.
The basic structure is as follows:
try:
# Code that may raise an exception
result = 10 / 2
except ZeroDivisionError:
# Code to handle the specific exception
print(“Cannot divide by zero!”)
else:
#Code to run in case no exceptions occur
print(f”Result: {result}”)
finally:
#Code to run irrespective of whether an exception occurred
print(“This will always be printed.”)
In this example:
- The
try
block contains code that might raise aZeroDivisionError
. - If a
ZeroDivisionError
occurs, the control transfers to theexcept
block, and the specific exception handling code is executed. - If no exception occurs, the
else
block is executed, and it contains code that runs only when there is no exception. - The
finally
block is always executed, regardless of whether an exception occurred. This block is commonly used for cleanup operations.
Here’s another example with an exception occurring:
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code to handle the specific exception
print(“Cannot divide by zero!”)
else:
#Code to run in the absence of any exceptions
print(f”Result: {result}”)
finally:
#Code to run irrespective of whether an exception occurred
print(“This will always be printed.”)
In this case, since a ZeroDivisionError
occurs, the except
block is executed, and then the finally
block is also executed.
The finally
block is often used for cleanup operations, such as closing files or releasing resources, ensuring that certain code is executed whether an exception occurs or not.
Handling Multiple Exceptions in One Block:
n Python, you can handle multiple exceptions in a single except
block by specifying the exceptions within parentheses. This allows you to provide a common handling routine for different types of exceptions.
Here’s an example:
try:
# Code that may raise exceptions
result = int(“abc”)
result = 10 / 0
except (ValueError, ZeroDivisionError) as e:
# Code to handle multiple exceptions
print(f”An exception occurred: {e}”)
In this example:
- The
try
block contains code that may raise either aValueError
or aZeroDivisionError
. - The
except
block catches both exceptions and prints a generic message along with the exception information.
You can catch as many exceptions as needed within the same except
block, separating them with commas:
try:
# Code that may raise exceptions
result = int(“abc”)
result = 10 / 0
except (ValueError, TypeError) as ve:
# Code to handle ValueError or TypeError
print(f”ValueError or TypeError: {ve}”)
except ZeroDivisionError as zd:
# Code to handle ZeroDivisionError
print(f”ZeroDivisionError: {zd}”)
except Exception as e:
# Code to handle any other exceptions
print(f”An exception occurred: {e}”)
In this example:
- The first
except
block handles bothValueError
andTypeError
. - The second
except
block handlesZeroDivisionError
. - The third
except
block is a generic catch-all for any other exceptions.
Note that the order of except
blocks matters. Python will execute the first block whose exception type matches the raised exception.
Handling multiple exceptions in one block is useful when you want to provide a common response to different types of errors or when you want to minimize redundant code.