Python OOPs


Examples


Others

Python Exception Handling


Exception handling is the way to handle the runtime errors.In Python, runtime errors can be handle using try and except block.

Syntax
try:
  #Block of code
except:
  #Handle the error
else:
  #Execute if no exception
finally:
  #Execute always executes 
Example
try:
    a=10
    c=a+b
    print(c)
except Exception as e:
    print(e)
finally:
    print("Program Complete")
Output
name 'b' is not defined Program Complete
Try except with else block
try:
    a=int(input("Enter Number 1: "))
    b=int(input("Enter Number 2: "))
    c=a/b
except Exception as e:
    print(e)
else:
    print("Result :",a)
Output
Enter Number 1: 25 Enter Number 2: 5 Result : 25
Common Exceptions Handling
try:
    a=10/0#ZeroDivisionError

    x=int("a")#ValueError

    x={"Name":"Tom"}
    print(x["age"])#KeyError

    add()#NameError
    a=10+"ad"#TypeError

    s=[1,2,4]
    print(s[5])#IndexError

    f=open("sample.txt","r")#IOError

except ZeroDivisionError as err:
    print(err)
except ValueError as err:
    print(err)
except KeyError as err:
    print(err)
except NameError as err:
    print(err)
except TypeError as err:
    print(err)
except IndexError as err:
    print(err)
except IOError as err:
    print(err)