Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
Exception handling is a crucial part of writing robust and maintainable code. In Python, the try
and except
blocks are used to handle exceptions that may occur during the execution of your program. By catching and handling exceptions, you can prevent your program from crashing and take appropriate action when errors occur.
In this tutorial, we will go over the basics of using try
and except
blocks in Python for exception handling.
try: # Code that might raise an exception result = 10 / 0 except ZeroDivisionError: # Code to handle the exception print("An error occurred: division by zero")
In this example, the code inside the try
block might raise a ZeroDivisionError
exception. If it does, the code inside the except
block will be executed, handling the exception.
try: # Code that might raise an exception result = 10 / "5" except (ZeroDivisionError, TypeError): # Code to handle the exception print("An error occurred: division by zero or invalid operand type")
In this example, the try
block might raise a ZeroDivisionError
or a TypeError
exception. If either occurs, the code inside the except
block will be executed.
try: # Code that might raise an exception result = 10 / 0 except ZeroDivisionError as e: # Code to handle the exception print(f"An error occurred: {e}")
In this example, we catch the ZeroDivisionError
exception and access its instance using the as
keyword. This allows us to retrieve more information about the error.
try: # Code that might raise an exception result = 10 / 5 except ZeroDivisionError: # Code to handle the exception print("An error occurred: division by zero") else: # Code to execute if no exception was raised print("No errors occurred, result:", result)
In this example, if the try
block doesn't raise an exception, the code inside the else
block will be executed.
try: # Code that might raise an exception result = 10 / 5 except ZeroDivisionError: # Code to handle the exception print("An error occurred: division by zero") else: # Code to execute if no exception was raised print("No errors occurred, result:", result) finally: # Code to always execute, regardless of whether an exception was raised print("The try-except block has finished executing")
In this example, the finally
block contains code that will always be executed, regardless of whether an exception was raised or not.
In this tutorial, you learned how to use try
and except
blocks in Python for exception handling. By incorporating these constructs into your code, you can catch and handle exceptions, preventing your program from crashing and allowing you to take appropriate action when errors occur. This helps you create more robust and maintainable code.
How to use try-except for error handling in Python:
try
and except
blocks are used to handle exceptions and prevent program termination.try: # Code that may raise an exception result = 10 / 0 except ZeroDivisionError: print("Error: Division by zero")
Common exceptions in Python and how to handle them with try-except:
ZeroDivisionError
, ValueError
, etc., using try-except
.try: num = int("not_an_integer") except ValueError: print("Error: Invalid conversion to integer")
Nested try-except blocks in Python:
try-except
blocks for handling exceptions at different levels of code.try: try: result = 10 / 0 except ZeroDivisionError: print("Inner try block: Division by zero") except Exception as e: print(f"Outer try block: {type(e).__name__} - {e}")
Handling multiple exceptions in a single try-except block:
try-except
block.try: value = int("not_an_integer") except (ValueError, TypeError): print("Error: Invalid conversion to integer")
Raising and catching exceptions with try-except in Python:
try-except
.class CustomError(Exception): pass try: raise CustomError("An example custom exception") except CustomError as ce: print(f"Caught custom exception: {ce}")
Using else and finally with try-except in Python:
else
and finally
blocks with try-except
for additional functionality.try: result = 10 / 2 except ZeroDivisionError: print("Error: Division by zero") else: print("No exception occurred, result:", result) finally: print("This block always executes")
Conditional exception handling with try-except in Python:
value = "not_an_integer" try: result = int(value) except ValueError if not value.isdigit() else TypeError: print("Error: Invalid conversion to integer")
Handling specific exceptions in Python with try-except:
except
blocks.try: result = 10 / 0 except ZeroDivisionError: print("Error: Division by zero") except ValueError: print("Error: Invalid value")
Graceful degradation with try-except in Python:
try: data = fetch_data_from_api() except APIError as e: print(f"API Error: {e}") data = get_default_data()
Debugging with try-except in Python:
try-except
for debugging by capturing and printing detailed error information.try: # Code with potential errors result = 10 / 0 except Exception as e: print(f"Error occurred: {type(e).__name__} - {e}")
Error logging in Python using try-except:
logging
module within try-except
blocks.import logging try: # Code that may raise an exception result = 10 / 0 except Exception as e: logging.error(f"Error occurred: {type(e).__name__} - {e}")
Exception propagation in Python with try-except:
def inner_function(): result = 10 / 0 def outer_function(): try: inner_function() except ZeroDivisionError: print("Error in inner_function") outer_function()