Menu Close

Python Exception Handling

Python exception handling

Hi Python Developers, In this article, we will learn all about Python’s most important concept that is called Python exception handling. Exception occurring in the program is one of the most common problems faced by most programmers but after this article, you will be able to handle exceptions in your program.

There are two types of errors occurred in the program, First is a Syntax error and the second is an Exception.

Syntax Errors:- Syntax errors are mistakes in the source code such as spelling mistake punctuation errors, incorrect labels, and so on, which cause an error message raised by the compiler.

Example


a = 12
b = 10
if a > b
    print(f"{a} is greater than {b}")

When the above program is executed a syntax error will occur.

Output

  File "C:\Users\Vishvajit\Desktop\PF Article\Python Basic part1\test.py", line 3
    if a > b
           ^
SyntaxError: invalid syntax

Exception:- An exception is an event that occurs during the execution of the program and disrupts the normal flow of the program’s instructions.

Example


a = 12
result = a / 0
print("The output is:- ", result)

When the above program has been executed an exception will have occurred.

Output

Traceback (most recent call last):
  File "C:\Users\Vishvajit\Desktop\PF Article\Python Basic part1\test.py", line 2, in <module>
    result = a / 0
ZeroDivisionError: division by zero

Is Exception Handling Important ?

Yes, Exception should be handled specially when are going to work with a real-life project and you are working with a software-based company as a programmer because exception handling made your code more neat and clean as well as your code looing more attractive.

Python provides three keywords try, except and finally that is capable to handle any type of exception in an easy way.

Python Try, Except and Finally Statement

There are three types of statements available in Python to handle any type of exception in Python.
Let’s understand all these statements one by one.

try:- Statements that can be raised an exception are kept inside the try block.

except:- Statement that handles the exception is kept inside except block.

finally:- Statements inside finally block always execute regardless of the result of the try and except block.

Python Exception Handling

When errors and exceptions occur in the program, Python will normally stop the program and generate a message. This exception can be handled inside the try block.

Example


try:
    a = 12
    result = a + b
    print("The result is:- ", result)
except:
    print("Exception raised!")

As you know that in the above program, b is not defined.try block generate and an exception because b is not defined. When the above program is executed the output will look like this.

The output will be:- Exception raised!

When the try and except block will not be defined inside the above program, the program will crash and raise an error.

Catching Multiple Exceptions

You can also catch more than one exception. To handle multiple exceptions you have to define multiple exception blocks.

Example


try:
    a = 12
    result = a + b
    print("The result is:- ", result)
except NameError:
    print("b is not defined!")
except:
    print("Something went wrong")

Handline Specific Exception

There are multiple types of exceptions available, you can handle the specific exceptions.

Syntax:


try:
    # statements
except ExceptionName:
    # statements

Example: Handling Specific Exception


try:
    a = 20
    result = a / 0
    print("The result is:- ", result)
except ZeroDivisionError:
    print("Something went wrong")

When the above program will be executed the ZeroDivisionError exception will occur and the output will be “Something went wrong“.

Else

You can also define else block to be executed if no errors were raised.

Example: Try Except with Else Python


try:
    a = 12
    b = 2
    result = a + b
    print("The result is:- ", result)
except:
    print("Something went wrong!")
else:
    print("Everythong gone good!")

Output

The result is:-  14
Everythong gone good!

Finally

The code inside the finally block will always execute when exceptions occur or not.

Example: No Exception Occur


try:
    a = 12
    b = 2
    result = a + b
    print("The result is:- ", result)
except:
    print("Something went wrong!")
finally:
    print("Always run!")

Output

The result is:-  14
Always run!

Example: Exception Occurs


try:
    a = 12
    result = a + b
    print("The result is:- ", result)
except:
    print("Something went wrong!")
finally:
    print("Always run!")

Output

Something went wrong!
Always run!

Finally, a block is useful to close up the object and clean up the resources.

Raise an exception

As a developer, you can also throw your own custom message as an exception using the raise keyword.

Example: Raise an Exception


number = int(input("Please, eneter any number:- "))
if number < 10:
    raise Exception("number, should be greater than 10!")
else:
    print(f"You enetered {number}")

Catch Error Message

You can also catch the error message using the Exception keyword.

Example


try:
    a = 12
    result = a + b
    print("The result is:- ", result)
except Exception as e:
    print("Exception raised:- ", e)

Output

Exception raised:- name ‘b’ is not defined

Conclusion

So, in this article, you have seen all about Python exception handling with try and except block with the help of various examples. This is one of the most important concepts of any programming language especially when you are working with real-life projects.

I strongly recommend you, always handle exceptions when you are writing code because Python exception handling will make you a good programmer and your code will look neat, clean, and more attractive.

I hope this article will have helped you, If you like this article don’t forget to share and keep visiting for further Python interesting tutorials.

Reference:- Click Here

Thanks for your valuable time … 👏👏👏

Python Lambda ( Anonymous ) Function
Types of Inheritance in Python

Related Posts