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 an essential part of writing robust and maintainable code in Python. It helps you handle errors and unexpected situations gracefully, ensuring your program doesn't crash due to unhandled exceptions.
In this tutorial, we will cover the basics of exception handling in Python, including try
, except
, else
, finally
, and raising exceptions.
try
and except
:The try
block is used to wrap the code that might raise an exception. If an exception occurs, the code inside the except
block will be executed. You can catch specific exceptions or use a general except
block to catch all exceptions.
try: result = 10 / 0 except ZeroDivisionError: print("An error occurred: Division by zero is not allowed")
You can catch multiple exceptions by specifying them in parentheses or by using multiple except
blocks.
try: # Some code that might raise an exception result = 10 / 0 except (ZeroDivisionError, TypeError): print("An error occurred") # OR try: # Some code that might raise an exception result = 10 / 0 except ZeroDivisionError: print("An error occurred: Division by zero is not allowed") except TypeError: print("An error occurred: Invalid data type")
else
:The else
block is executed if the code inside the try
block doesn't raise an exception.
try: result = 10 / 2 except ZeroDivisionError: print("An error occurred: Division by zero is not allowed") else: print(f"The result is: {result}")
finally
:The finally
block is executed no matter what, whether an exception is raised or not. It's often used to release resources, close files, or perform cleanup tasks.
try: result = 10 / 2 except ZeroDivisionError: print("An error occurred: Division by zero is not allowed") else: print(f"The result is: {result}") finally: print("This will always be executed")
Use the raise
keyword followed by an exception class or an instance of an exception to raise an exception manually. You can also raise an exception in an except
block to re-raise the caught exception after performing some tasks.
def divide(a, b): if b == 0: raise ValueError("Division by zero is not allowed") return a / b try: result = divide(10, 0) except ValueError as e: print(f"An error occurred: {e}")
In this tutorial, you learned the basics of exception handling in Python, including using try
, except
, else
, finally
, and raising exceptions. By incorporating exception handling in your code, you can create more robust and resilient programs that can handle errors and unexpected situations gracefully.
Nested try-except
blocks in Python:
try: try: result = 10 / 0 except ZeroDivisionError: print("Inner: Cannot divide by zero") result = None except Exception as e: print(f"Outer: An error occurred: {e}")
Raising exceptions in Python:
def example_function(value): if value < 0: raise ValueError("Value must be non-negative") # Rest of the code...
Exception handling for file operations in Python:
try: with open("nonexistent_file.txt", "r") as file: content = file.read() except FileNotFoundError: print("File not found")
Using else
and finally
with try-except
in Python:
try: result = 10 / 2 except ZeroDivisionError: print("Cannot divide by zero") else: print(f"Result: {result}") finally: print("Execution completed")
Error logging in Python exception handling:
import logging try: result = 10 / 0 except ZeroDivisionError as e: logging.error(f"Error occurred: {e}")
Exception chaining in Python:
try: result = 10 / 0 except ZeroDivisionError as e: raise ValueError("Custom error") from e
Custom exception classes in Python:
class CustomError(Exception): pass try: raise CustomError("This is a custom error") except CustomError as e: print(f"Caught custom error: {e}")
Graceful degradation and exception handling in Python:
Handle exceptions gracefully to prevent the entire program from crashing.
def divide(a, b): try: result = a / b except ZeroDivisionError: print("Cannot divide by zero") result = None return result
Python exception handling for beginners:
Beginners should focus on understanding common exceptions, handling them step by step, and improving over time.
Debugging with Python exception traceback:
The traceback provides information about the sequence of function calls that led to the exception.
def function_a(): result = 10 / 0 def function_b(): function_a() try: function_b() except Exception as e: import traceback traceback.print_exc()
Handling specific exceptions in Python:
try: result = int("abc") except ValueError: print("Invalid conversion to integer") except Exception as e: print(f"An unexpected error occurred: {e}")