Table of contents

Error Handling and Exceptions

Errors and exceptions are a part of any programming language. They occur when something goes wrong during the execution of a program. Understanding how to handle these errors and exceptions is crucial for creating robust and reliable programs. This guide will cover the basics of error handling and exceptions in Python, with detailed explanations and examples.

There are mainly two types of errors in Python:

  • Syntax Errors: These are errors in the syntax of the code. They are detected by the Python interpreter when the code is parsed and must be corrected before the code can run.

Example:

print("Hello, World!" # Missing closing parenthesis
  • Exceptions: These are errors that occur during the execution of a program. They can be caught and handled to prevent the program from crashing.

Example:

print(10 / 0) # ZeroDivisionError

The try block lets you test a block of code for errors. The except block lets you handle the error.

Syntax:

try: # Code that may cause an exception except SomeException: # Code to handle the exception

You can catch specific exceptions to handle different types of errors differently.

Example:

try: value = int(input("Enter a number: ")) result = 10 / value except ValueError: print("That's not a valid number!") except ZeroDivisionError: print("You can't divide by zero!")

You can catch multiple exceptions in a single except block by specifying a tuple of exception types.

Example:

try: value = int(input("Enter a number: ")) result = 10 / value except (ValueError, ZeroDivisionError) as e: print(f"An error occurred: {e}")

The else block lets you execute code if no exceptions were raised.

Example:

try: value = int(input("Enter a number: ")) result = 10 / value except (ValueError, ZeroDivisionError) as e: print(f"An error occurred: {e}") else: print(f"Result: {result}")

The finally block lets you execute code, regardless of whether an exception was raised or not. It’s typically used to release resources, such as closing a file.

Example:

try: file = open("example.txt", "r") content = file.read() except FileNotFoundError: print("File not found!") else: print(content) finally: if file: file.close()

You can raise exceptions using the raise keyword. This is useful for enforcing certain conditions in your code.

Example:

def check_age(age): if age < 0: raise ValueError("Age cannot be negative!") return age try: user_age = check_age(-5) except ValueError as e: print(e)

You can define your own exceptions by creating a new class that inherits from the built-in Exception class.

Example:

class CustomError(Exception): pass def check_value(value): if value > 100: raise CustomError("Value cannot be greater than 100!") try: check_value(150) except CustomError as e: print(e)

Write a program that handles both ValueError and ZeroDivisionError in a division operation.

def divide_numbers(): try: numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) result = numerator / denominator except ValueError: print("Invalid input! Please enter numbers only.") except ZeroDivisionError: print("You can't divide by zero!") else: print(f"Result: {result}") divide_numbers()

Write a program to read a file and handle the FileNotFoundError exception.

def read_file(file_name): try: with open(file_name, 'r') as file: content = file.read() print(content) except FileNotFoundError: print("The specified file was not found!") read_file("example.txt")

Create a custom exception called NegativeValueError and use it to validate that a user input is not negative.

class NegativeValueError(Exception): pass def get_positive_number(): try: number = int(input("Enter a positive number: ")) if number < 0: raise NegativeValueError("Number cannot be negative!") except NegativeValueError as e: print(e) except ValueError: print("Invalid input! Please enter a number.") else: print(f"You entered: {number}") get_positive_number()

Write a program that asks for two numbers and performs division. Handle exceptions for invalid input and division by zero.

def safe_division(): try: num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) result = num1 / num2 except ValueError: print("Invalid input! Please enter valid numbers.") except ZeroDivisionError: print("You can't divide by zero!") else: print(f"The result is: {result}") safe_division()

In this comprehensive guide, we’ve covered the basics of error handling and exceptions in Python. By understanding how to handle different types of errors, you can create more robust and reliable programs. Practice these concepts with the provided examples and exercises to strengthen your understanding. Happy coding!