Error handling is a crucial aspect of writing robust python code. Python provides several ways to handle errors and exceptions gracefully. This blog explores various techniques to manage errors effectively in Python.
Try-Except Block: This is the fundamental way to handle errors in python. It allows you to catch and handle exceptions without terminating the program. Use when you are unsure if a block of code might raise an exception.
try: result = 10/0 except ZeroDivisionError as e: print(f"Error: {e}")
Try-Except-Else Block: The else block can be used along with try-except. The else block executes only if no exceptions occurred within the try block. Use when you want to execute certain code only if no exception occurs in the try block.
try: result = 10/2 except ZeroDivisionError as e: print(f"Error: {e}") else: print(f"Result is: {result}")
Try-Finally Block: The finally block executes code regardless of whether an exception occurred or not. Commonly used for cleanup tasks like closing files or releasing resources. Use when you need to ensure that some cleanup code runs no matter what.
try: file = open("sample.txt","r") data = file.read() except FileNotFoundError as e: print(f"Error: {e}") finally: if 'file' in locals(): file.close() print("File closed")
Raising Exceptions: You can manually raise exceptions using the raise keyword. This is useful when you want to enforce certain conditions in your code.
def validate_number(num): if num<0: raise ValueError("Number cannot be negative.") elif num>100: raise ValueError("Number cannot be more than 100.") else: print(f"It's good number {num}") try: validate_number(-2) except ValueError as e: print(f"Error: {e}")
Assertions: Assertions are used to test assumptions in your code. They are mainly used during development for debugging purposes.
def divide_num(x,y): assert y!=0, "Division by zero is not allowed" return x/y try: result = divide_num(4,0) print(f"Result is {result}") except AssertionError as e: print(f"Error: {e}")
Custom Exceptions: Creating custom exceptions can make your error handling more meaningful and specific to your application’s needs.
class CustomError(Exception): pass def risky_fun(): raise CustomError("Something wrong") try: risky_fun() except CustomError as e: print(f"Error: {e}")