Topic 9 – Error and Exception Handling in Python

image 2

Play Store Application link – Java to Python in 17 Steps – App on Google Play

Github project link – https://github.com/kuldeep101990/Python_step9

In the world of programming, errors are inevitable. They happen for a variety of reasons like incorrect input, network failures, or resource unavailability. The key to writing resilient applications is understanding how to handle errors. In this blog post, we’ll explore Python’s error and exception handling mechanisms and compare them with Java. Since you’re already familiar with Java, we’ll draw comparisons wherever possible and keep the focus on practical code examples.

1. Python’s try-except vs. Java’s try-catch

Java:

In Java, you handle exceptions using the try-catch block. The general syntax looks like this:

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
}

For example, if you are dividing two numbers and one of them is zero, you might get an ArithmeticException:

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
}

Python:

In Python, we use try-except blocks to catch exceptions. The syntax is almost the same but more concise:

try:
    # Code that might throw an exception
except ExceptionType as e:
    # Code to handle the exception

For example, dividing by zero in Python:

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print("Cannot divide by zero!")

Real-World Scenario: File Operations

Let’s say you are reading data from a file. If the file doesn’t exist, we’ll get an error.

Java Example:

try {
    FileReader file = new FileReader("nonexistent.txt");
    BufferedReader fileInput = new BufferedReader(file);
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
}

Python Example:

try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError as e:
    print("File not found!")

Both examples handle the case where the file does not exist, but Python makes file handling easier with the with statement (which automatically closes the file after usage).

2. Finally Block

In both Python and Java, you can use a finally block to execute code that should always run, whether or not an exception occurs.

Java:

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("This will always run.");
}

Python:

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print("Cannot divide by zero!")
finally:
    print("This will always run.")

3. Raising Exceptions: raise vs. throw

In Java, you use throw to explicitly raise an exception, while in Python, the keyword is raise.

Java:

if (age < 18) {
    throw new IllegalArgumentException("Age must be 18 or above");
}

Python:

if age < 18:
    raise ValueError("Age must be 18 or above")

Both raise an exception when a condition is met, but Python uses raise while Java uses throw.

4. Custom Exceptions in Python

Custom exceptions allow you to create more meaningful error messages specific to your application. Both Java and Python allow this, but the syntax varies.

Java:

In Java, you create custom exceptions by extending the Exception class:

public class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}
try {
    throw new InvalidAgeException("Age is below the minimum required.");
} catch (InvalidAgeException e) {
    System.out.println(e.getMessage());
}

Python:

In Python, you can create custom exceptions by subclassing the Exception class:

class InvalidAgeException(Exception):
    def __init__(self, message):
        super().__init__(message)
try:
    raise InvalidAgeException("Age is below the minimum required.")
except InvalidAgeException as e:
    print(e)

5. Complete Python Program for Error Handling

Now that we’ve understood the basics of error and exception handling, let’s create a simple Python program that demonstrates these concepts. The program will simulate a scenario where a user inputs their age, and the system will raise an exception if the age is invalid or below the minimum allowed age.

class InvalidAgeException(Exception):
    def __init__(self, message):
        super().__init__(message)
def get_age():
    age = input("Please enter your age: ")
    try:
        age = int(age)
        if age < 18:
            raise InvalidAgeException("Age must be 18 or above!")
        print(f"Your age is: {age}")
    except ValueError:
        print("Invalid input! Please enter a valid number.")
    except InvalidAgeException as e:
        print(e)
    finally:
        print("End of age validation.")
if __name__ == "__main__":
    get_age()

How the Program Works:

  1. The program prompts the user to enter their age.
  2. If the input is not a valid number, it catches the ValueError and prints an error message.
  3. If the age is below 18, it raises a custom InvalidAgeException.
  4. The finally block always runs, ensuring the end message is printed regardless of what happens.

Summary

  • Python and Java have similar ways to handle exceptions, but Python uses simpler syntax.
  • try-except in Python corresponds to try-catch in Java.
  • The finally block ensures certain code always runs, regardless of exceptions.
  • You can raise exceptions in Python with raise and in Java with throw.
  • Custom exceptions allow you to make your application-specific error messages.

This comparison should help you transition smoothly between Python and Java, especially when it comes to error and exception handling. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *