Try, Except and Finally In Python

Published by Anshul Verma on

No matter how good you are at programming, there will be errors in certain scripts. These errors might occur because of unexpected user input, an erroneous server response or any other reason. Try Except in Python allows you to catch errors and, instead of dying, do something more reasonable. In this article, we will see how Python uses the try-except to handle the exception in the following sequence:

  • What is Try Except in Python?
  • How does Try work?
  • Python Exceptions Example
  • Exception Handling
  • Exception Errors
  • Try…except Python: Multiple Except Statements
  • Try…except Python: Finally
  • Raise Keyword in Python
  • Conclusion

What is Try Except in Python?

The Try method is used in Error and Exception Handling. There are two kinds of errors :

  • Syntax Error: It is also known as Parsing Error. This occurs when the Python parser is unable to understand a line of code.
  • Exception Error: These errors are detected during execution.

Now, in these situations, we need to handle these errors within our code in Python. That is where try-except in python comes handy.

Syntax:

Example:

How Does Try() Work?

The different steps involved in the working of try are:

  • The try clause is executed between the try and except clause.
  • If there is no exception, then only the try clause will run and except clause is finished.
  • The try clause will be skipped and except clause will run if any exception occurs.
  • In case of any exception, if the except clause within the code doesn’t handle it, it is passed on to the outer try statements. The execution is stopped if the exception left unhandled.
  • try statement can have more than one except clause.

Python Exceptions Example

In the first example, there is no exception, so the try clause will run:

In the second example, there is an exception so only except clause will run:

Exception Handling

The try and except block in Python is used to catch and handle exceptions. Python executes a code considering the try statement as a normal part of the program. Whereas, the except statement acts as the program’s response to any exceptions in the preceding try clause.

Exceptions are convenient for handling errors and special conditions in a program. If you are working with a code that can produce an error then you can use exception handling. Also, you can raise an exception in your own program by using the raise exception statement. Raising an exception breaks current code execution and returns the exception back until it is handled.

Exception Errors

There are different types of Exception Errors such as:

  • IOError: If the file cannot be opened
  • KeyboardInterrupt: When an unrequired key is pressed by the user
  • ValueError: When the built-in function receives a wrong argument
  • EOFError: If End-Of-File is hit without reading any data
  • ImportError: If it is unable to find the module

Try…except Python: Multiple Except Statements

You can repeat except statements for different types of errors to test for multiple exceptions. This is useful if you suspect that one of many exceptions may be raised but you are not sure which one you will encounter.

Here is an example of try…except blocks that look for a NameError:

In this case, our code returns ourVariable is not defined because our code returns a NameError. We could add more errors, such as a ZeroDivisionError or an OSError, depending on the code we are testing.

For instance, you may check for an IOError and a FileNotFoundError if you want to open a file. Checking for multiple exceptions would ensure your program could continue running even if there was an error opening the file you reference.

Try…except Python: Finally

But what if we want a message to print both if an error is returned and if no error is found? That’s where the finally block comes in. If you define a finally clause, its contents will be executed irrespective of whether the try…except block raises an error.

Finally blocks are a useful indicator that you code has executed. Because they do not differentiate between whether a code has successfully executed, they are not as commonly used.

Here’s an example:

The code within the except block executes because there is an exception found in our code (ourVariable is not defined). The code within the finally clause executes as well, because our code has finished running.

Raise Keyword in Python

Sometimes, you may want to deal with a situation by raising a certain exception. A simple print statement won’t work here.

Let’s take our case of division.

Here, we convert the inputs to a and b to integers. Then, we check if b is 0. In that case, we raise a ZeroDivisionError.

Conclusion

Try…except blocks make it easy to debug your Python code. A program tries to run the code in a “try” block. If this fails, the “except” block runs. The code in a “finally” statement runs irrespective of whether an “except” block is executed. In this tutorial, we have broken down how to use try…except blocks. We have discussed how to use else and except to customize your exception handling. These blocks can be useful when you’re testing existing code or writing new code. It ensures that your program runs correctly and contains no errors.

With this, we have come to the end of our article. I hope you understood what is try except in Python and how it is used for handling exceptions.

Till then, Stay Safe, Stay Happy & Keep Coding…

IF YOU WANT TO KNOW ABOUt DATA SCIENCE click here.

CONNECT WITH THE AUTHOR ON LINKEDIN.

VISIT OUR WEBSITE BRIGHTERBEES FOR MORE INTERESTING STUFFS ABOUT LEARNING.


0 Comments

Leave a Reply

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

STAY CONNECT WITH US