Exception Handling



Exception

Errors occur when something goes wrong. We have encountered several errors in our program such as index out of bounds error, division by zero error. The errors in python programming categorized as syntax errors and exception. A syntax error occurs when the rule of python grammar is violated.
        An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.

For example:

print("Engine-4-Geeks)
A syntax error occurs in the print function because of missing quote mark at the end of the string.

Handling Exception:

If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try block. After the try block, include an except statement, followed by a block of code which handles the problem as elegantly as possible.

Syntax:

try:
    operations here
except:
    exception arises,then execute this code
else:
    If there is no error then execute this block

For example:

def divide():
    n1=int(input("Enter Number 1: "))
    n2=int(input("Enter Number 2: "))
    try:
        div=n1/n2
    except:
        print("You can not divide by zero")
    else:
        print("Answer is : ",div)
divide()



Raising Exception:







Post a Comment

0 Comments