AppDividend
Latest Code Tutorials

Python Try Except Example | Exception Handling in Python

0

Python Try Except Example | Exception Handling in Python is today’s topic. An exception is an error that happens during the execution of a program. When that error occurs, Python generates an exception that can be handled, which avoids your program to crash. Exceptions are a convenient way of handling errors and particular conditions in the program. If you think that you have a code which can produce an error, you should use exception handling mechanism.

What are exceptions in Python?

Python has many built-in exceptions which force your program to output an error when something in it goes wrong. 

When these exceptions occur in the program, it causes the current process to stop and passes it to a calling process until it is appropriately handled.

If the python exceptions not handled, then our python program will crash.

Raising an Exception in Python

We can use the raise to throw an exception if the condition occurs.

The statement can be complemented with the custom exception.

If you want to throw the error when the particular condition occurs using raise, you can write the code like below.

# app.py

el = 11
if el > 10:
    raise Exception('el should not exceed 10. The value of x was: {}'.format(x))

See the output.

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 3, in 
    raise Exception('el should not exceed 10. The value of x was: {}'.format(x))
NameError: name 'x' is not defined
➜  pyt

The execution comes to a halt and displays our exception to screen, offering the clues about what went wrong.

An AssertionError Exception

Instead of waiting for the program to crash in the midway, you can also start by making the assertion in Python.

We assert that the specific condition is met.

If the condition turns out to be True, then it is excellent! The program can continue.

If the condition turns out to be False, then you can have the program throw the AssertionError exception.

See the following code.

# app.py

import sys

assert ('linux' in sys.platform), "This piece of code runs on Linux only."

If you run this code on the Linux machine, the assertion passes.

If you are running this code on the Windows machine or Mac like me, the outcome of an assertion would be False, and the result would be the following.

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 3, in 
    assert ('linux' in sys.platform), "This piece of code runs on Linux only."
AssertionError: This piece of code runs on Linux only.
➜  pyt

Python Try Except Example

The try block lets you test the block of code for possible errors. 

In Python language, exceptions can be handled using the try statement.

The critical operation which can raise the exception is placed inside the try clause, and the code that handles an exception is written in except clause.

The except block lets you handle an error.

The finally block you execute code, regardless of the result of the try-except blocks.

When the error occurs, or exception, Python stops executing the program and generate an error message.

Let us see a simple example.

# app.py

try:
    print(k)
except:
    print('One error has been thrown')

In the above code, we have not defined k variable so, the try block raises an error and the except block will be executed, and we see the output in the console.

Python Try Except Example | Exception Handling in Python

Now, if we do not write the try-except block, then python program will crash and raise an error. See the following example.

# app.py

print(k)

Exception Handling in Python

Exception Handling in Python

If we need to use exception handling in Python, we first need to have a catch-all except clause. The words ‘try’ and ‘except’ are Python keywords and are used to catch exceptions.

The syntax is following.

try:
    some statements here
except:
    exception handling code here

See the following example.

# app.py

try:
    print(21/0)

except ZeroDivisionError:
    print ('You can\'t divide anything by zero, Exception Found')

So, here the try block raises an exception and except block catch that exception and run the code of except block which is to print the message in the console.

try-except else clause in Python

The else clause in the try-except statement must follow all the except clauses, and it is useful for the code that must be executed if the try clause does not raise an exception.

try:
     operation_that_can_throw_ioerror()
except IOError:
     handle_the_exception_somehow()
else:
     # we don't want to catch the IOError if it's raised
     another_operation_that_can_throw_ioerror()
finally:
     something_we_always_need_to_do()

try-finally clause in Python

Let’s take a scenario in which you always had to implement some action to clean up after executing the code.

Python enables you to do so using the finally clause.

If the finally block specified, it will be implemented regardless of the try block raises an error or not.

# app.py

try:
    print(21/0)

except ZeroDivisionError:
    print ('You can\'t divide anything by zero, Exception Found')

finally:
    print('finally block is executed')

try-finally clause in Python

try except finally python example

See the following code.

# app.py

import sys


def linux_check():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')


try:
    linux_check()
except AssertionError as error:
    print(error)
else:
    try:
        with open('error.log') as file:
            read_data = f.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('It will print irrespective of any exceptions.')

If you are executing this code on the Linux machine, you will get the following output.

Doing something.
[Errno 2] No such file or directory: 'error.log'

From the output, you can see that the linux_check() function ran because there were no exceptions encountered and then attempt to open error.log was made.

The error.log file does not exist, and instead of opening a file, you caught a FileNotFoundError exception.

Otherwise, like me on mac or windows, you will get the following result.

➜  pyt python3 app.py
Function can only run on Linux systems.
It will print irrespective of any exceptions.
➜  pyt

In the previous code, everything in the finally clause will be executed.

It does not matter if you encounter the exception somewhere in the try or else clauses.

List of Exception Errors :

  1. IOError: If the file can’t be opened.
  2. KeyboardInterrupt: When the user presses an unrequired key.
  3. ValueError: When the built-in function receives the wrong argument.
  4. EOFError: If the End-Of-File is hit without reading any of the data.
  5. ImportError: If it is unable to find a module.

You can find more about Exception Handling on python’s official docs.

Keypoints 

  1. The try clause is executed up until the point where the first exception is encountered.
  2. Inside the except clause or the exception handler, you determine how a program responds to the exception.
  3. You can anticipate multiple exceptions and differentiate how the program should respond to them.
  4. Avoid using bare except clauses. The reason is the catching Exception hides all errors…even those who are entirely unexpected. That is why you should avoid bare except clauses in your Python programs. Instead, you’ll want to refer to particular exception classes you want to catch and handle.

Conclusion

Now, you have learned about various ways to raise, catch, and handle exceptions in Python. Let’s refresh what we have learned.

  1. The raise allows you to throw an exception at any time.
  2. An assert enables us to verify if the certain condition is met and throw the exception if it isn’t.
  3. In the try clause, all statements are executed until the exception is encountered.
  4. The except is used to catch and handle the exception(s) that are encountered in a try clause.
  5. The else lets you code sections that should run only when no exceptions are encountered in the try clause.
  6. finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions.

Finally, Python Try Except Example | Exception Handling in Python is over.

Recommended Posts

Recursion In Python Programming Tutorial

Python Operators Example

Python Not Equal Operator Example

Python property() Example

File open() Function In Python

pow() Function In Python Tutorial

iter() Function In Python Tutorial

Python next() Example

Python Null Value Tutorial

Inheritance In Python

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.