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.

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 <module>
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?

ExceptionCause of Error
AssertionErrorRaised when assert statement fails.
AttributeErrorRaised when attribute assignment or reference fails.
EOFErrorRaised when the input() functions hit end-of-file condition.
FloatingPointErrorRaised when a floating point operation fails.
GeneratorExitRaise when a generator’s close() method is called.
ImportErrorRaised when the imported module is not found.
IndexErrorRaised when the index of a sequence is out of range.
KeyErrorRaised when a key is not found in a dictionary.
KeyboardInterruptRaised when the user hits interrupt key (Ctrl+c or delete).
MemoryErrorRaised when an operation runs out of memory.
NameErrorRaised when a variable is not found in the local or global scope.
NotImplementedErrorRaised by abstract methods.
OSErrorRaised when system operation causes system related error.
OverflowErrorRaised when the result of an arithmetic operation is too large to be represented.
ReferenceErrorRaised when a weak reference proxy is used to access a garbage collected referent.
RuntimeErrorRaised when an error does not fall under any other category.
StopIterationRaised by next() function to indicate that there is no further item to be returned by the iterator.
SyntaxErrorRaised by the parser when a syntax error is encountered.
IndentationErrorRaised when there is incorrect indentation.
TabErrorRaised when indentation consists of inconsistent tabs and spaces.
SystemErrorRaised when interpreter detects an internal error.
SystemExitRaised by sys.exit() function.
TypeErrorRaised when a function or operation is applied to an object of the incorrect type.
UnboundLocalErrorRaised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeErrorRaised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeErrorRaised when a Unicode-related error occurs during encoding.
UnicodeDecodeErrorRaised when a Unicode-related error occurs during decoding.
UnicodeTranslateErrorRaised when a Unicode-related error occurs during translating.
ValueErrorRaised when a function gets the argument of correct type but improper value.
ZeroDivisionErrorRaised 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,<value>
Let us use the following example to raise error:-
try:
    age = int(input("Enter the age: "))
    if age < 18:
        raise ValueError
    else:  
        print("The age is valid")

except ValueError:
    print("The age is not valid")
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
SHARE Python Exception Handling

You may also like...

Leave a Reply

Your email address will not be published.

Share