Understanding Exception Handling in Python

Understanding Exception Handling in Python

Blog | Board Infinity
Blog | Board Infinity

What is an Exception in Python

An event that occurs during the execution of the program and obstructs the regular flow of the program's instructions is an exception. A Python script typically raises an exception when it comes across a situation that it cannot handle. A Python object that represents an error is called an exception.
When a Python script encounters an exception, it must either deal with it right away or quit and stop working.

Code Example of an Exception

Let's take an example code when an exception occurs when we try to divide a number with 0.

a = 100

print(a/0)

Output

Traceback (most recent call last):

  File "./prog.py", line 2, in <module>

ZeroDivisionError: division by zero

Handling an Exception

If your program contains any suspicious code that could cause an exception, you can protect it by enclosing it in a try: block. Include an except: statement after the try: block, then a block of code that solves the issue as elegantly as possible.

Code Example of an Exception Handling:

Let's take an example code where we are handling the above ZerDivisionError Exception.

try:

    a = 100

    print(a/0)


except:

    print("There is some error in your code")

Output:

There is some error in your code

Catching and Handling specific Exceptions:

To specify handlers for various exceptions, a try statement may contain more than one except clause. Please be aware that only one handler will be run at a time. The standard syntax for adding particular exceptions is:

Syntax

try:

    # statement(s)

except ZeroDivisionError:

    # statement(s)

except ValueError:

    # statement(s)

Example: let's take an example code where we are handling ZeroDivisionError Specifically.

try:

    a = 100

    print(a/0)


except ZeroDivisionError:

    print("You can divide any number by 0")


except:

    print("An Unknown Error Has Neen Occured")

Output

You can divide any number by 0

Try with Else Clause

Python also supports the else clause, which must come after all except clauses, in the try-except block. Only when the try clause fails to throw an exception does the code move on to the else block.

Example

Let's take an example code where we are handling the exception with the else clause.

try:

    a = 100/1


except ZeroDivisionError:

    print("You can divide any number by 0")


else:

    print(a)

Output

100.0

Finally Keyword in Python

The finally keyword is available in Python, and it is always used after the try and except blocks. The final block is always executed after the try block has terminated normally or after the try block has terminated for some other reason.

Example

Let's take an example code where we are handling the exception using Finally Keyword.

try:

    a = 100/0


except ZeroDivisionError:

    print("You can divide any number by 0")


finally:

    print("Finally always runs")

Output

You can divide any number by 0

Finally always runs

Raising Exceptions in Python

We can also raise exceptions in Python for our needs. This can be done using raise keyword.

Example

Let's take an example code where we are raising our custom exception.

try:

    raise MyException("A Custom Exception is Raised")


except MyException:

    print("My Custom Exception")

Output

Traceback (most recent call last):

  File "./prog.py", line 2, in <module>

NameError: name 'MyException' is not defined


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "./prog.py", line 4, in <module>

NameError: name 'MyException' is not defined

Python

Blog | Board Infinity

At Board Infinity we have authors leading in their profession sharing their insights, ideas and inspiration. Here influential thinkers, creators, makers and doers are found in one place.