top of page

Exception Handling

Handling an error is an important of any program. we can achieve it with the help of try and except keywords in python.

Try Except

try:

    a = 5

    b = 10

    print(c)

    print(a+b)

except:

    print("Error occurred")

try part will run, till the program does not encounter any error. once the error occurs in try part, it will come out of the try block and except will be printed.

Else

try:

    a = 5

    b = 10

    print(a+b)

except:

    print("Error occurred")

else:

    print("no error occurred")

if no error occurred in a try block then else part will be printed and if error occurred than except part will be printed.

finally

try:

    a = 5

    b = 10

    print(c)

    print(a+b)

except:

    print("Error occurred")

else:

    print("no error occurred")

finally:

    print("program completed successfully")

finally will run at the end of the program irrespective of the error occurred or not.

bottom of page