Catch & Display Exception in Python with Examples
In programming, any event that interrupts a running program is known as Exception. Exception can be any error like: Division by Zero Error, Index Out of Range Error, Value Error, Type Error etc.
In python these exceptions are named as ZeroDivisionError, IndexError, ValueError, TypeError etc. and are known as Built-in Exceptions. All exceptions in python are derived from class BaseException
.
Catching and displaying exception is very important in programming. It helps to prevent program from being interrupted due to various error.
In this article we are going to write simple python program which can catch and display exception.
Catch & Display Exception
To catch any exceptions in python we need to put code which is likely to raise an exception within try
block. This try block is followed by except
block which can catch any Exception object using Exception as e
. Now exception object is named as e
which can be displayed using built-in output function print(e)
.
Example: Catch & Display Exception
try:
value = 0/0
except Exception as e:
print("Exception: ", e)
Output
The output of the above program is:
Exception: division by zero