Python try except and finally

Python try except and finally - exceptional handling

 

An exception is a very known to every programmer! Afterall we most of the time seems to be playing with this keyword. Python try except and finally statements allow you to handle these exceptions.

 

Python exception or error doesn’t indicate that there is always something wrong with the logic or algorithm. 

 

There are some circumstances where your program is absolutely correct, still you encounter run-time error that situation is known as an EXCEPTION.

 

At this point, our run time errors resulted in a termination of program execution. Rather terminating the program execution, program could detect the error before hand and handle it in a very smart way, that concept is called as Exceptional handling.

 

An Exceptional handling is a standard python mechanism allows programmers to deal with the run-time errors. 

 

Examples of exceptional errors: integer division by zero, attempting to convert a non-number to an integer, accessing a list with an out-of-range index, and using an object reference set to None.

 

Few common python exceptions are described here but if you want to go through all the exception list then visit this page Python built-in Exception.

 

1. ZeroDivisionError: division by zero

You have a program where you are doing some calculations. You have defined two integer variables and assigned value to them. Now you are trying to attempt division operation.

N1=int(input(“Enter first Number – N1 :”))

N2=int(input(“Enter Second Number – N2 :”))

Result=N1/N2

print(“Result :”, Result)

Your code is absolutely perfect, and it will give you division answer but what will happen if user enters 0 value for variable N2! Always remember, you never have a control over an end user. 

 

In this case program execution will be terminated with error – ZeroDivisionError: division by zero

Output

Enter first Number – N1 :100

Enter Second Number – N2 :0

Traceback (most recent call last):

File “C:/Users/Python37/exceptional_handling.py”, line 3, in

Result=N1/N2

ZeroDivisionError: division by zero

>>>


2. ValueError: invalid literal for int()

To continues with same above example where you expect user should enter integer number(digits) but consider user has entered some random characters or numbers in a word (say five instead of 5) for variable N1 then WHAT? It will throw this exception – ValueError: invalid literal for int()

Enter first Number – N1 :five

Traceback (most recent call last):

 File “C:/Users/Python37/exceptional_handling.py”, line 1, in <module>

 N1=int(input(“Enter first Number – N1 :”))

ValueError: invalid literal for int() with base 10: ‘five’

>>> 


3. OverflowError: integer division result too large for a float

To continues with the same example, now user has entered very large number for variable N1. Observe what happened with your result – error OverflowError: integer division result too large for a float

python exception handling OverflowError



Looking for Solution?

Yes, it is absolutely possible to write a code to avoid such kind of errors in python like other programming languages, but python has unique features which you can apply.

 

Python has built in conditional execution structure to handle the situation where you might encounter expected or unexpected run-time errors.


Python Try and except

try/except block to be added where you think potential exception can occur in your program. 


Syntax:

try:

 #It contains code that might raise an exception.

except:

 #It contains code to execute Only when try block raise an exception.

 

Back to our previous example and we will see how it works. Now you know where possible exception error can come in our example so try to add try/except block into it.

 

Firstly, we will try display text message to the user so they can understand what went wrong! The technical error user might not understand so let’s change default error message with simple plain English text.

try:

 N1=int(input(“Enter first Number – N1 :”))

 N2=int(input(“Enter Second Number – N2 :”))

 Result=N1/N2

 print(“Result :”, Result)

except ValueError:

 print(“Oops!! Seems you have entered invalid Number”)

except OverflowError:

 print(“Oops-ERROR!! Result value seems to be too large to display”)

print(“Program execution continues….”)

 

Scenario #1

Enter first Number – N1 :five

Oops!! Seems you have entered invalid Number

Program execution continues….

>>> 

Scenario #2

python try except exception handling



Summary

  • Program execution doesn’t terminate when you use try except block and exception occurs.
  • An except block doesn’t execute unless try block don’t raise an exception.
  • Multiple except block can be written for one try block.



Python else

 

If try block raise an exception, then only except block gets executed otherwise else block will be executed.

In other words, else block only executed when try block do not raise an exception.

 

try:

 N1=int(input(“Enter first Number – N1 :”))

 N2=int(input(“Enter Second Number – N2 :”))

 Result=N1/N2

 print(“Result :”, Result)

except ValueError:

 print(“Oops!! Seems you have entered invalid Number”)

else:

print(“Division Successful!”)

print(“Program execution continues….”)



Python finally

finally block always executes after try/except block execution. It does nothing extraordinary, just creates the space for you to execute something after try/except block.

try:

 N1=int(input(“Enter first Number – N1 :”))

 N2=int(input(“Enter Second Number – N2 :”))

 Result=N1/N2

 print(“Result :”, Result)

except ValueError:

 print(“Oops!! Seems you have entered invalid Number”)

finally:

print(“Executing finally…block!”)

print(“Program execution continues….”)

 

So far, we have seen basic use of try/except, else and finally block in python. Mostly it is being used with the conditional loop statements and allow users to try one more time – with proper message on screen when they enter wrong values, for instance.


Example

Write a program to demonstrate an exceptional handling case with Loop statements!

In this example users can input any small integer value less than 100. They can enter number greater than 100 to complete the program execution. This code will not fail or terminate the execution if try block raise ValueError exception.

x = 0

while x < 100:

 try:

 # I hope the user enters a valid Python integer!

 x = int(input(“Please enter small integer Number: “))

 print(“x =”, x)

 except ValueError:

 print(“Oops!! Input cannot be parsed as an integer – Please try again”)

print(“Program finished”)

 

Output

Please enter small integer Number: 25

x = 25

Please enter small integer Number: 50

x = 50

Please enter small integer Number: five

Oops!! Input cannot be parsed as an integer – Please try again

Please enter small integer Number: 5

x = 5

Please enter small integer Number: 200

x = 200

Program finished

>>> 

 

Read More: Python raise Keyword
Spread the love

Leave a Comment