Python – Exception Handling
Python Exception Handling – An exception is an error that occurs at the runtime of any python program. When any runtime error occurs program stops executing the rest of the program and flashes an error message.
Syntax error can be detected by the compilers or interpreter but logical error and exception errors can not be detected by the compilers.
Python provides methods to handle such situations and that is called exception handling. The syntax of exception handling in python is as follows
try: code 1 exception: code 2 else: code3 finally: code4
code1: This is the code that may produce an error at runtime code 2: This code will execute when code1 will produce an error at runtime code 3: This code will execute when code1 execute and does not produce any error at runtime code 4: This code will execute all the time, whether code produces an error at runtime or not but this code will run always
A sample code that is written using try exception
a = 10 b = int(input("Enter any number ")) try: c = a/b except: print('Cannot divide NUMBER by STRING')
Explanation of Try exception block
Put only the code that could generate run time error. Otherwise will not do anything.
if you want to print the output of the above program if there is no output on the screen. Now we want to show
the output if everything is fine.
a = 10 b = int(input("Enter any number ")) try: c = a/b except: print('Cannot divide NUMBER by STRING') else: print('Result :',c)
Enter any number 2 Result : 5.0 Enter any number 0 Cannot divide NUMBER by STRING Enter any number 3 Result : 3.3333333333333335
Now one more keyword is also available ie finally. The statements finally always execute whether there is an exception or not.
Sample Python Program to show the use of finally keyword.
a = 10 b = int(input("Enter any number ")) try: c = a/b except: print('Cannot divide NUMBER by STRING') else: print('Result :',c) finally: print('End of Python Program')
The above try block will catch all the errors that will occur at runtime but if you want to raise your own exception on the certain situation then you have to define that exception separately.
a = 10 b = int(input("Enter any number ")) try: if(b==0): raise exception c = a/b except Exception e: print('Your Divisor is ZERO') except DivideByZero: print('Trying to divide your number by Zero'); else: print('Result :',c) finally: print('End of Python Program')
SO here in this program segment, we are trying to catch only two types of exceptions only. This way you can define your own exception in Exception Handling.
Hope this example will help you to understand Exception handling in Python.