It is good practise to handle exceptions(unexpected data) in the code to avoid arbitrarily termination of the program. Python provides a way to handle unexpected values passed to the code, popular exception example: division by Zero.
There are four main building blocks(rather five, 1 for custom exceptions) for exception handling:
Exception Handling Block
try:
some_code
some_code
except [HandleSpecificError]:
some_code_to_inform_user_of_error_OR_some_action
except:
some_code_if_the error_is_different_than_any_of_the_specific_exceptions
some_code_to_inform_user_of_error_OR_some_action
[else:
optional_else_for_Some_code_if_no_error_occured
]
[finally:
optional_finally_for_Some_code_which will_always_execute_regardless_of_error_occured_or_not.
]
try:
print("Hello Dbmstutorials")
except:
print("Exception Raised!")
Output:
Hello Dbmstutorial
try:
print("Hello Dbmstutorials"+1)
except:
print("Exception Raised!")
Output:
Exception Raised!
try:
print(print_undefineVariable)
except NameError:
print("NameError: Variable is not defined")
Output: NameError: Variable is not defined
try:
a=2
print("num "+a) #trying to append integer to the String
except NameError:
print("NameError: Variable is not defined")
except TypeError:
print("TypeError: Improper type value used")
Output: TypeError: Improper type value used
try:
print(1/0)
except ZeroDivisionError:
print("Division by zero detected")
Output: Division by zero detected
try:
a=[3,4,5,7]
print(a[4]) #index 4 is not present since Python list starts from 0
except IndexError:
print("IndexError: Index not found")
Output: IndexError: Index not found
import io
try:
a=open("~/test.dml")
except IOError:
print("IOError: Error reading file")
Output: IOError: Error reading file
import time
try:
time.dbmstutorials(100) # dbmstutorials is not attribute of time module
except AttributeError:
print("AttributeError: undefined attribute used")
Output: AttributeError: undefined attribute used
import time
try:
print("Press Ctrl + C after 10 seconds")
time.sleep(100) #Sleep for 100 seconds
except KeyboardInterrupt:
print("KeyboardInterrupt: Interrupted by user with Ctrl+C")
Output: ^CKeyboardInterrupt: Interrupted by user with Ctrl+C
try:
a=2
print("num "+a)
except ZeroDivisionError:
print("ZeroDivisionError: Divide by Zero Exception")
except IndexError:
print("IndexError: Index not found")
except:
print("TypeError Exception handled by Except ")
Output:
TypeError Exception handled by Except
try:
print("num "+a) #trying to append undefined variable
except (NameError, TypeError):
print("NameError: Variable is not defined OR TypeError: Improper type value used")
except:
print("TypeError Exception handled by Except ")
Output:
NameError: Variable is not defined OR TypeError: Improper type value used
try:
print("Hello Dbmstutorials")
except:
print("Exception Raised")
else:
print("No Exception Raised")
Output:
Hello Dbmstutorials
No Exception Raised
try:
print("Hello Dbmstutorials"+1)
except:
print("Exception Raised")
else:
print("No Exception Raised")
Output: Exception Raised!
try:
print("Hello Dbmstutorials")
except:
print("Exception Raised")
finally:
print("Finally is executed")
Output:
Hello Dbmstutorials
Finally is executed
try:
print("Hello Dbmstutorials"+1)
except:
print("Exception Raised!")
finally:
print("Finally is executed")
Output:
Exception Raised!
Finally is executed
try:
a=6
if (a==6):
raise Exception
except Exception:
print("Custom Exception Raised")
Output:
Custom Exception Raised
Python 3:
try:
a=6
if (a==6):
raise Exception(a)
except Exception as except_val:
print("Type of the exception variable "+str(type(except_val)))
print("This is value for custom raised exception variable "+str(except_val))
Output:
Type of the exception variable <type 'exceptions.Exception'>
This is value for custom raised exception variable 6
Python 2.7:
try:
a=6
if (a==6):
raise Exception(a)
except Exception, except_val:
print("Type of the exception variable "+str(type(except_val)))
print("This is value for custom raised exception variable "+str(except_val))
Output:
Type of the exception variable <type 'exceptions.Exception'>
This is value for custom raised exception variable 6
Note: Syntax is different in old versions of Python(2.7) and in Python 3
Python 3:
try:
a=6;b=3
if (a==6 and b < a):
raise Exception(a , b)
except Exception as except_val:
print("Value for custom raised exception variables "+str(except_val))
c,d= except_val.args
print("Value of c ="+str(c)+ " and value of d ="+str(d))
Output: Value for custom raised exception variables (6, 3)
Value of c =6 and value of d =3
Python 2.7:
try:
a=6;b=3
if (a==6 and b < a):
raise Exception(a , b)
except Exception, except_val:
print("Value for custom raised exception variables "+str(except_val))
c, d = except_val
print("Value of c ="+str(c)+ " and value of d ="+str(d))
Output: Value for custom raised exception variables (6, 3)
Value of c =6 and value of d =3
Note: Syntax is different in old versions of Python(2.7) and in Python 3
Python 3:
try:
a=6;b=3;c=39
if (a==6 and b < a):
raise Exception(a , b, c)
except Exception as except_val:
print("Type of the exception variable "+str(type(except_val)))
dTuple = except_val.args
print("Type of the dTuple variable "+str(type(dTuple)))
print("Value of the dTuple variable "+str(dTuple))
Output:
Type of the exception variable <type 'exceptions.Exception'>
Type of the dTuple variable
Value of the dTuple variable (6, 3, 39)
Python 2.7:
try:
a=6;b=3;c=39
if (a==6 and b < a):
raise Exception(a , b, c)
except Exception, except_val:
print("Type of the exception variable "+str(type(except_val)))
dTuple = except_val.args
print("Type of the dTuple variable "+str(type(dTuple)))
print("Value of the dTuple variable "+str(dTuple))
Output:
Type of the exception variable <type 'exceptions.Exception'>
Type of the dTuple variable
Value of the dTuple variable (6, 3, 39)
Note: Syntax is different in old versions of Python(2.7) and in Python 3