Skip to main content

Exception Handling

Errors:
A programming mistake is said to be an error.

There are three types of errors:
1) Compile time errors
2) Run time errors
3) Logical errors

Compile time errors are also called syntax errors.
Run time errors are also called exceptions.

Example of syntax error:
i=0
if i==0 
   print(i)
In the above example we have missed the : symbol after if statement. It is called as syntax error.

Example of exception:
a=10
b=0
print(a//b)
In the above example ZeroDivisionError occurs. It is called as an exception.

This type of exceptions can be handled explicitly to display user friendly error messages.

Handling Exceptions:
Syntaxes:
1) try with except block:
    try:
         ========
    except ExceptionClassName:
        ========

2) try with multiple except blocks:
    try:
         ==========
    except ExceptionClassName1:
        ===========
    except ExceptionClassName2:
        ===========

3) Multiple exceptions in a single block:
    try:
         ==========
    except(ExceptionClassName1, ExceptionClassName2, ........)
         ==========

4) except block without exception class name
    try:
        ==========
    except:
        ==========

Examples:
1) 
try:
    a=int(input("Enter First Number: "))
    b=int(input("Enter Second Number: "))
    c=a//b
    print(c)
except ZeroDivisionError:
    print("Enter Second Number Except Zero")

2)
try:
    a=int(input("Enter First Number: "))
    b=int(input("Enter Second Number: "))
    c=a//b
    print(c)
except ValueError:
    print("Enter Numbers Only")
except ZeroDivisionError:
    print("Enter Second Number Except Zero")

3) 
try:
    a=int(input("Enter First Number: "))
    b=int(input("Enter Second Number: "))
    c=a//b
    print(c)
except(ZeroDivisionError, ValueError):
    print("Enter two numbers and second number except zero")

4) 
try:
    a=int(input("Enter First Number: "))
    b=int(input("Enter Second Number: "))
    c=a//b
    print(c)
except:
    print("Enter two numbers and second number except zero")