Python Exception Handling

Python exceptions are handle by try..except finally,else keywords.
Syntax:
try:
            statements;
except ExceptionI:
   exception statements;
except ExceptionII:
   exception statements;
else:
   If there is no exception then execute this block.
finally:
            raised irrespective of raised an error.

Built in Exceptions


Exception

Cause of Error

AssertionError

Raised when assert statement fails.

AttributeError

Raised when attribute assignment or reference fails.

EOFError

Raised when the input() functions hits end-of-file condition.

FloatingPointError

Raised when a floating point operation fails.

GeneratorExit

Raise when a generator's close() method is called.

ImportError

Raised when the imported module is not found.

IndexError

Raised when index of a sequence is out of range.

KeyError

Raised when a key is not found in a dictionary.

KeyboardInterrupt

Raised when the user hits interrupt key (Ctrl+c or delete).

MemoryError

Raised when an operation runs out of memory.

NameError

Raised when a variable is not found in local or global scope.

NotImplementedError

Raised by abstract methods.

OSError

Raised when system operation causes system related error.

OverflowError

Raised when result of an arithmetic operation is too large to be represented.

ReferenceError

Raised when a weak reference proxy is used to access a garbage collected referent.

RuntimeError

Raised when an error does not fall under any other category.

StopIteration

Raised by next() function to indicate that there is no further item to be returned by iterator.

SyntaxError

Raised by parser when syntax error is encountered.

IndentationError

Raised when there is incorrect indentation.

TabError

Raised when indentation consists of inconsistent tabs and spaces.

SystemError

Raised when interpreter detects internal error.

SystemExit

Raised by sys.exit() function.

TypeError

Raised when a function or operation is applied to an object of incorrect type.

UnboundLocalError

Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.

UnicodeError

Raised when a Unicode-related encoding or decoding error occurs.

UnicodeEncodeError

Raised when a Unicode-related error occurs during encoding.

UnicodeDecodeError

Raised when a Unicode-related error occurs during decoding.

UnicodeTranslateError

Raised when a Unicode-related error occurs during translating.

ValueError

Raised when a function gets argument of correct type but improper value.

ZeroDivisionError

Raised when second operand of division or modulo operation is zero.

 

Program on ZeroDiviison Error

a=10;
b=0;
try:
c=a/b;
print(c);
except ZeroDivisionError:
print("Divide by zero");

 program on multiple exceptions and else

a=10;
b=10;
s=[5,4,2,66,5,44];
try:               
c=a/b;
print(c);
print(s[12]);
except ZeroDivisionError:
print("Divide by zero");

except IndexError:
print("index out of range exception");
else: # this will execute when there is no error
print("This is else block");

except: this block should be last except block in multiple except blocks. If the exception is unknown we can use this block.

program on default except

import sys;
a=10;
b=10;
s=[5,4,2,66,5,44];
try:      
c=a/b;
print(c);
print(s[12]);

except ZeroDivisionError:
print("Divide by zero");

except:
print(sys.exc_info()[0]);
print(sys.exc_info()[1]);

 

program on nested try statements

a=10;
b=2;
s=[5,4,2,66,5,44];
try:
c=a/b;
print(c);
try:
if b==1:
c=a/(b-1);
if b==2:
print(s[12]);
except IndexError:
print("index out of range exception");
except ZeroDivisionError:
print("Divide by zero");
else:
print("This is els block");

 

Multiple exceptions in except clause
We can use a tuple of values to specify multiple exceptions in an except clause.

Programe on multiple except clause

import sys;
a=10;
b=10;
s=[5,4,2,66,5,44];
try:      
c=a/b;
print(c);
print(s[12]);

except (ZeroDivisionError,IndexError):
print("Divide by zero / index error");

 

Raising Exceptions using raise keyword

we can forcefully raise it using the keyword raise.
We can also optionally pass in value to the exception to clarify why that exception was raised.

Program on raising exception

import sys;
try:
a=int(input("Etner number"));
if a>10:
raise ValueError("Value is greater than 10");
print("given value",a);
except ValueError as e:
print(e);

Program on finally and else

import sys;
try:
a=int(input("Enter number"));
if a>10:
raise ValueError("Value is greater than 10");
print("given value",a);
except ValueError as e:
print(e);
else:  #this block will execute when threre is no error
print("This is else block");

finally:  # this will execute irrespective or raised an error.
print("this is finally"); 

User-Defined Exception

Users can create their own exception classes using exception class

Program on user defined Exception

class myexcept(Exception):

def __init__(self,a):
x=a;

a=(input("Enter number"));
try:
if int(a)>25:
raise myexcept(a);
print(a);
except myexcept as e:
print("value is more than ",e);

 

For
More Explanation
&
Online Classes

Contact Us:
+919885348743