Exceptions and Exception Handling in Python

An exception is an event that happens during program execution that disrupts the normal execution of the program.

Exceptions happen when there’s a problem during the execution of a program. In order to prevent exceptions or provide an alternative course of action when they happen, there comes the need for exception handling.

Exceptions can be handled while errors cannot be handled.

Exceptions are errors that occur not because the syntax is incorrect, but are introduced by the data upon which your code is working on.

When exceptions occur, from the error messages, you’ll be able to get clues on the reasons behind the errors.

In order words, exceptions prevent the rest of the program from executing and that’s why it’s important to anticipate them in advance and handle them properly and not allow them to disrupt the program flow.

Exceptions Handling in Python

Exceptions are handled in Python using the try-except block. This way, you instruct Python to do something if exceptions occur.

try except block

With this block, you can show users a friendly message of what happened, rather than allowing Python to display messy tracebacks which are usually hard to comprehend.

By anticipating likely sources of error and catching them, you can be able to write robust programs.

Python searches for an except block that matches the exception raised and executes the code contained within that block.


try:

    print('hello')

except:

    print('exception occured!')

If an exception didn’t occur, the except block will be skipped and lines in the try block will be executed. If an exception occurs, every other code is skipped except those in the except block.

You can also indicate the various kinds of errors to catch in the except block. Here are some of the likely exceptions you may likely catch using the except block.

  • IndexError
  • TypeError
  • NameError
  • ZeroDivisionError
  • FileNotFoundError

You can also have nested except clauses as shown below:


try:

    print('hello')

except ValueError:

    print('exception occured!')

except:

    print('exception occured!')

else block

The try-except block also has an optional else clause. The else clause executes if the try clause did not raise any error. It’s often used to ensure that the file is closed after reading or writing.


try:

    print('hello')

except:

    print('error found')

else:

    print('completed')

#hello

#completed

finally clause

The try block also has an optional finally clause. Statements inside this clause must be executed under all circumstances.

It usually executes as the last clause in the try block.


try:
    result = 5/0
    print(result)
except:
    print('exception occured')
else:
    print('no exception found')
finally:
    print('completed')

#output
#exception occured
#completed

Raising exceptions

There may be times when you would have good reasons to raise an exception deliberately in your program. Hence, the keyword raise is used to raise exceptions in python

try:

    raise ValueError('Value error raised!')

except ValueError as e:

    print(e)

#Value error raised!

User-defined exceptions

Exceptions are derived from the Exception class.

You can create a user-defined exception by either creating your own exception class or inheriting from the exception class and modifying it.


class CustomError(Exception):

    pass

try:

    raise CustomError

except CustomError:

    print('Custom Exception')

#Custom Exception

Leave a Reply

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