Exception Handling in Python
Exception Handling in Python
1. Exception Handling.
2. Assertions.
Standard Exceptions
EXCEPTION NAME DESCRIPTION
Exception Base class for all exceptions
ArithmeticError Base class for all errors that occur for numeric
calculation.
ZeroDivisonError Raised when division or modulo by zero takes place for
all numeric types.
EOFError Raised when there is no input from either the
raw_input() or
input() function and the end of file is reached.
ImportError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts program execution,
usually by pressing Ctrl+c.
NameError Raised when an identifier is not found in the local or
global namespace.
SyntaxError Raised when there is an error in Python syntax.
EXCEPTION NAME DESCRIPTION
IndentationError Raised when indentation is not specified properly.
TypeError Raised when an operation or function is attempted that
is invalid for the specified data type.
Exception Handling
• The suspicious code can be handled by using the try block.
• Enclose the code which raises an exception inside the try
block.
• The try block is followed by except clause.
• It is then further followed by statements which are executed
during exception and in case if exception does not occur.
Try •Code in which exception may occur
fun(11) # 11
fun("string")
#argument is not a number invalid literal for int() with base 10: 'string’
Example 2
def fun(a,b):
c= a/b
return c
try:
fun("a","b")
except TypeError as VE:
print("Exception: ",VE)
Output:
Exception: unsupported operand type(s) for /: 'str' and 'str'
Raising Exception
• The raise statement allows the programmer to force a specific
exception to occur.
• The sole argument in raise indicates the exception to be raised.
• This must be either an exception instance or an exception class (a
class that derives from Exception).
# Program to depict Raising Exception
try:
raise NameError("Hey! are you sleeping!") # Raise Error
except NameError as NE:
print (NE)
try:
raise Exception("How are you")
except Exception as E:
print(E)
OUTPUT:
point is ORIGIN (0,0)