Python Exceptions and Exception Handling

In case of an error, a good program should be able to recover from it. And if it is not possible to recover from the error, then your program should report it in an appropriate manner to the user. We’ll learn what are Python Exceptions and how to write code for handling exceptions in Python.

Python Exceptions

What are Python Exceptions?

When an error occurs at run-time, Python raises an exception. This is when your program crashes. That is, the interpreter terminates the execution of your program and displays an error message on the screen.

But those big red errors don’t look quite good on the screen, right?

To avoid that, Python allows us to handle these exceptions in our own way so that our program doesn’t terminate abruptly.

Catching Exceptions in Python

Python raises an exception when a run-time error occurs. If your program doesn’t have code to take care of a raised exception, we say that the exception is uncaught. In that case, the interpreter will terminate your code and then display an error message.

That said, we can also catch a raised exception. But catching an exception is not enough, we also have to decide what to do next. That is, we need to provide an alternate flow of execution. You can either run some other code in place of the crashed code. Or you can display a clean error message and terminate your application.

This is the magic of Exception Handling, you can choose what happens when an exception occurs.

Follow TechVidvan on Google & Stay updated with latest technology trends

Let’s code it – The try … except statement

At the core of it, the try … except statement allows you to react whenever a part of your code results in an exception.

Place the code which can potentially raise an exception inside the try clause. And put the alternate code or a friendly error message inside the except clause.

Let’s look at an example where we try to open a file. But what if the file doesn’t exist in our system? We don’t want those big red scary error messages to pop up on the screen again, remember? So we’ll indent the code for opening the file under the try statement. And the alternate code/error message goes under the except clause.

try:
    f = open("file.txt")
    print(f.read())
    
except:
    print("Error while opening the file")

Output

“Error while opening the file”

The interpreter starts executing the code under the try clause.

  • If no exception occurs, it ignores the except block and executes the rest of the code until it hits the end of the program.
  • If an exception raises in the try clause, the flow of execution jumps to the except clause immediately.

We can also specify which exception our except clause will handle.

Code to catch specific exception:

try:
    f = open("file.txt")
    print(f.read())
    
except FileNotFoundError:
    print("Error while opening the file")

This feature of handling specific exceptions is useful when multiple exceptions can occur in your try code. We can either use multiple except clauses in that case, or we can specify multiple exceptions in a single except clause.

Code to catch multiple exceptions using multiple except clauses:

try:
    x = int(input("Enter the numerator: "))
    y = int(input("Enter the denominator: "))
    print("The quotient is: ", x/y)
    

except ZeroDivisionError:
    print("Can't divide by zero")

except ValueError:
    print("Please provide a valid integer value")

Code to catch multiple exceptions using a single except clause:

try:
    x = int(input("Enter the numerator: "))
    y = int(input("Enter the denominator: "))
    print("The quotient is: ", x/y)
    

except (ZeroDivisionError, ValueError):
    print("Please provide a valid integer value")

 

Adding Python Finally clause

It is optional to add the finally clause in Python. Even if an exception occurs or not, the code indented under the finally clause always executes.

We usually use the finally clause to perform “clean-up” actions. For example, we need to close the file we were operating on in the try clause.

try:
    f = open("file.txt")
    print(f.read())
    
except FileNotFoundError:
    print("Error while opening the file")

finally:
    f.close()

Raising Exceptions in Python

One of the many superpowers of exception handling is that it can let us decide when to raise a specific exception in our code. We can also provide a custom message while raising an exception.

For Example

try:
    x = input("Enter choice(yes/no): ")
    if x != 'yes' and x != 'no':
        raise ValueError("Invalid choice. Please enter yes or no.");


except ValueError as e:
    print(e)

Output:

Enter choice(yes/no): ad
Invalid choice. Please enter yes or no.
>>>

User-Defined Exceptions in Python

Python lets you create custom exceptions as well. You can define your own exception by creating a new class. Every user-defined exception class has to inherit from the Exception class.

Example code:

class MyException(Exception):
    pass

That’s literally all you need to do for creating your own exception! Now we have a custom exception “MyException”. We can raise this exception in our try clause. For Example:

class MyException(Exception):
    pass

try:
    my_list = [1, 2, 3, 4, 5]
    x = int(input("Enter an integer: "))
    if x not in my_list:
        raise MyException

except MyException:
    print("The number you entered is not present within the list.")

Output:

Enter an integer: 7
The number you entered is not in the list.

Summary

This brings up to the end of the article. We learned what exceptions are and how we can handle them. We also looked at various ways of using the try … except clause. We learned all about raising and catching exceptions. We got to know how important the finally clause can be at times. And lastly, we saw how we can create user-defined exceptions.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google | Facebook


Leave a Reply

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