There come many situations during the writing of a program that we are not really sure whether the code is correct to perform a specific task. At the same time, we do not want any error situation during runtime because of the same unsure code.

To tackle this type of problem exception handling is used in python. Let’s see what is it and how to implement it in our program.

What is an Exception?

An exception is any unwanted situation which occurs during the runtime of a program. This stops the processing/execution of the program and if not properly handled then can result in a crash.

Example of one such exception in python is:

Here we tried to add two different types of values and as a result, we got TypeError.

TypeError is one of the type of Built-in-Exception in Python.

To handle these exception- try, except and finally comes handy. Let’s see how each of them work one by one.

Try Except Else in Python

Try Except Else is one of the ways to deal with the exception and to ensure smooth execution of the program.

The code which has the probability of error should be written in try block and the handling of these exceptions should be done in except block. Else only gets executed when there is no excetion in the code inside try block.

Syntax

Examples

Output

Output

Output

Try Except Finally in Python

Finally block always gets executed irrespective of exception in the try block.

Examples

Output

Output

Output

Output

Hope now you can use exception handling to handle exceptions using try, except, else and finally block.

Leave a Reply

Close Menu