Python Exception Handling – Try Except Else Finally

We are going to explore Python Exception Handling in this lesson. This will include discussing try/except blocks, try else, and try/except/finally block. We will also learn how to define your own python exception.

What is Exception Handling in Python?

When a Python script encounters an error, it raises an exception. An exception is a Python object that represents an error. If the script doesn’t handle the exception immediately, it will terminate.

An Exception is an event that interrupts the normal flow of execution. It is also known as a run time error. When that error occurs, Python generates an exception that can be handled, avoiding interruption to the program.

Example:

a = 7
b = 0

print (a/b)

Output:

Python Tutorial 15 - Try Exception ...
Python Tutorial 15 - Try Exception Handling
Traceback (most recent call last):
File "<stdin>", line 1, in <module>

ZeroDivisionError: division by zero

The system can’t divide the number by zero in this code, so an exception is thrown.

Python try, except, else, and finally

  • Try: This block will check for the error that was expected to happen.
  • Except: This block is where you can take care of the mistake.
  • Else: If there are no further errors, this block will be executed.
  • Finally: Whether an exception is made or not, the finally block is always executed.

Syntax:

try:

       # Some Code.... 

except:

       # optional block
       # Handling of exception (if required)

else:

       # executed if there's no exception

finally:

      # Some code .....(always executed)

Try/Except Blocks in Python

If you think your code might throw an exception, put it in a try block.

Example:

try:
     print(x)
except:
     print("An exception occurred.")

Output:

An exception occurred.

The except block will be executed because the try block raised an error. If there was no try block, the program would crash and raise an error.

Example:

print(x)

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined0

Python Multiple Excepts

There can be multiple except blocks for a single try block. Let’s look at some examples of how Python handles more than one exception.

Example:

try:
    print(x)

except NameError:
    print("Variable x is not defined")

except:
    print("Something else went wrong")

Output:

Variable x is not defined

The interpreter checks the except blocks to see if any of them can handle the exception when it encounters one. In our example, the first statement under the try block resulted in a NameError.

The try block contains code that may cause an error. The except block contains code that will be executed if an error occurs. If an error occurs, the code in the try block after the error will not be executed.

If an appropriate except block or a generic except block is not found, the exception will go unhandled.

Python Multiple Exception in one Except

You can also have one except block handle multiple exceptions by using parentheses.

Example:

try:
      print('50'+20)
      print(7/0)
except (TypeError,ZeroDivisionError):
      print("Invalid input")

Output:

Invalid input

Try/Else in Python

Using the else clause, you can specify a code block to be performed if no errors occurred:

Example: try block does not produce an error.

try:
      print("Python is Fun!")
except:
      print("There's an error")
else:
      print("No error")

Try/Except/Finally Block in Python

You can include a finally clause exception block after the last except block. This code will execute no matter what.

Example:

try:
     print(7/0)

except ValueError:
     print('Value Error is raised')

finally:
     print('Prints the finally block')

Output:

Prints the finally block
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

Raise Exceptions

You might need to throw an exception to handle a situation. You can throw an exception by using the raise keyword.

Example:

a = -6

if a < 0:
  raise Exception("Please input absolute values.")

Raise Without a Specified Exception in Python

You can use the raise keyword without specifying an exception, which will cause the original exception to be raised again. This can only be done inside an except block.

try:
         print('70'+10)

except:
         raise

Output:

Traceback (most recent call last):
         File "<stdin>", line 2, in <module>
TypeError: can only concatenate str (not "int") to str

Raise With an Argument in Python

You can also include an argument with the exception you’re raising, to give additional details about what happened.

Example:

raise ValueError("Enter a appropriate value")

Output:

Traceback (most recent call last):
         File "<stdin>", line 1, in <module>
ValueError: Enter a appropriate value

Assertions in Python

Python Assertions are statements that help you check if your code is correct by testing if specific conditions remain true. This can be useful when debugging code.

This function takes an expression as an argument. If the expression has a False Boolean value, it raises a python exception. Otherwise, it executes a No-operation (NOP).

assert(True)

What would happen if the expression were False?

Example:

assert(1==0)

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

Python Built-in Exceptions

Below is the list of all the Built-in Exceptions in Python. You can visit the Python official documentation about the Standard Exception if you want more information.

Exception NameDescription
ExceptionBase class for all exceptions
StopIterationThrown when an iterator’s next() method doesn’t point to any object.
SystemExitThe sys.exit() function raises this error.
StandardErrorExcept for StopIteration and SystemExit, this is the base class for all built-in exceptions.
ArithmeticErrorBase class for all errors that can happen when working with numbers.
OverflowErrorRaised when a calculation uses more numbers than a numeric type can handle.
FloatingPointErrorRaised when a calculation with a floating point number fails.
ZeroDivisionErrorRaised when any type of number is divided by zero or moduloed by zero.
Raised when the second argument of a division or modulo operation is zero
AssertionErrorIf the Assert statement fails, this event is raised.
AttributeErrorIf the reference or assignment of an attribute fails, this event is raised.
EOFErrorIf the reference or assignment of an attribute fails, this event is raised.
ImportErrorIf an import statement fails, this event is thrown.
KeyboardInterruptWhen the user stops the program from running, usually by pressing Ctrl+c, this signal is sent.
LookupErrorBase class for the exceptions that are thrown when a key or index used on a mapping or sequence is not valid.
IndexErrorThrown when a sequence can’t find an index.
KeyErrorRaised when the key does not exist in the dictionary.
NameErrorRaised when an identifier can’t be found in either the local or global namespace.
UnboundLocalErrorRaised when a reference tries to use a local variable in a function or method that hasn’t been given a value yet.
EnvironmentErrorThis is the base class for all exceptions that happen outside of Python.
IOErrorRaised when an input/output operation fails, like when the print statement or the open() function try to open a file that doesn’t exist.
SyntaxErrorRaised when there is a mistake in the way Python is written.
IndentationErrorRaised when indentation is not specified properly.
SystemErrorRaised when the interpreter finds an internal error. However, when this error is thrown, the Python interpreter does not close.
SystemExitWhen the sys.exit() function is used to stop the Python interpreter, this event is raised. If the code doesn’t handle it, it makes the interpreter quit.
TypeErrorThrown when an operation or function is tried that doesn’t work with the data type that was given.
ValueErrorAn error occurs when a built-in operation or function receives an argument that has the right type but an invalid value.
RuntimeErrorRaised when a mistake can’t be put into any of the other categories.
NotImplementedErrorThis error is shown when a class that has been inherited doesn’t implement an abstract method that it should.
List of Standard Exceptions in Python

Summary

In summary, an exception is a Python object that represents an error. There can be multiple except blocks for a single try block. You can throw an exception by using the raise keyword in Python. And assertions are statements that help you check if your code is correct.

And finally, if you missed any of our earlier lectures, you can always go to our Python Tutorial Topics list. In addition, if you want to learn more about machine learning, you can review our Best Machine Learning Projects with Source Code.


Leave a Comment