Python Exception Handling

As we start writing programs, we may encounter errors which are not basically a syntax error but run time errors, which cannot be predicted easily. So, there needs to be a mechanism to handle these kinds of errors so that the program doesn’t crash during the runtime. Errors that occur during the execution are known as exceptions.

Loading…

What happens when we do not handle exceptions in Python?

Let us have a look at the following example, where we take two input numbers from users and divide the first number by the second number:-

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = a / b
print("a/b = %d" % c)

print("Rest of the program")
Enter first number: 2
Enter second number: 0
Traceback (most recent call last):
File “test.py”, line 3, in
c = a / b
ZeroDivisionError: division by zero

So here, you can see ZeroDivisionError is the Exception being thrown. The program halts and the “Rest of the program” are not executed. To provide the user with a clearer message and make the program work after the exception too, we need to handle this with Python Exception Handling methods.

How do we handle Exception in Python?

Python provides try … except block to handling exception. The syntax for the exception handling is:-

try:
You do your operations here;
………………….
except Exception1:
If there is Exception1, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
………………….
else:
If there is no exception then execute this block.

Here the code inside try block is what we expect to produce an exception. The operations are done in the try block and if the exception occurs, the program moves to except block. Here, we can use multiple exceptions to provide an appropriate message to the user and also use else block if the exception is not caught.

Let us have an example to make it more clear on how can we handle these kind of exception in the above program:-

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
try:
    c = a / b
    print("a/b = %d" % c)
except ZeroDivisionError:
    print("can't divide by zero")
else:
    print("I am else block")

print("Rest of the program")

The output of the above program is:-

Enter first number: 2
Enter second number: 0
can’t divide by zero
Rest of the program
So you can see that the exception is caught and an appropriate message is displayed to the user. The “Rest of the program” is also printed.

How to define the exception clause with no exceptions in Python?

We can use except block only if we want to catch all the exceptions.

try:
You do your operations here;
………………….
except:
If there is any exception, then execute this block.
………………….
else:
If there is no exception then execute this block.

The except Clause with Multiple Exceptions

The except keyword can handle multiple exceptions too using comma separated values of exceptions.

try:
You do your operations here;
………………….
except(Exception1[, Exception2[,…ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
………………….
else:
If there is no exception then execute this block.

What is finally block in Python for exception handling?

You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not.

try:
You do your operations here;
………………….
Due to any exception, this may be skipped.
finally:
This would always be executed.
………………….
These exception handling can be better described using the following image.

What are the built-in exceptions in Python?

Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functions hit end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator’s close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when the index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in the local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
OverflowError Raised when the result of an arithmetic operation is too large to be represented.
ReferenceError Raised when a weak reference proxy is used to access a garbage collected referent.
RuntimeError Raised when an error does not fall under any other category.
StopIteration Raised by next() function to indicate that there is no further item to be returned by the iterator.
SyntaxError Raised by the parser when a syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects an internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an object of the incorrect type.
UnboundLocalError Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translating.
ValueError Raised when a function gets the argument of correct type but improper value.
ZeroDivisionError Raised when the second operand of division or modulo operation is zero.

How do we raise exceptions in Python?

To raise an exception during the program execution, we use raise keyword in Python. We can pass arguments to exception using a comma. The syntax to use the raise keyword is:-

raise Exception_class,
Let us use the following example to raise error:-
try:
    age = int(input("Enter the age: "))
    if age 
Enter the age: 8
The age is not valid

How to create a user-defined exception in Python?

We can create user-defined custom exception in Python by creating a class that extends the Exception class. Let us create a custom class for defining our exception.

class ErrorInCode(Exception):
    def __init__(self, data):
        self.data = data

    def __str__(self):
        return repr(self.data)


try:
    raise ErrorInCode(1300)
except ErrorInCode as ae:
    print("Received error:", ae.data)    

The output is:-

Received error: 1300
Loading...