Sunday, February 2, 2020

Python Exception Handling Tutorial

This Python exception handling tutorial gives an overview of Python exceptions and how to handle exceptions using Python exception handling.

Types of errors

Errors in your Python programs can be categorized into atleast two types-

  • Syntax errors
  • Exceptions

Syntax error

Syntax errors or compile time errors are the errors due to which your program fails to compile. Such errors are detected at the compile time itself, file name, line number and error description is displayed so you know where to look for the error and how to correct it.

For example if you don’t write colon after if statement-

def check_equality(str1, str2):
    if str1 > str2
        print(str1, 'is greater than', str2)

Then you get the compile time error as shown here-

Output

  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 2
    if str1 > str2
                 ^
SyntaxError: invalid syntax

Exceptions

Even if a statement or expression is syntactically correct it may result in an error at run time. Errors detected during runtime are called exceptions and they disrupt the normal execution flow of the program.

For example in the following program there is an attempt to divide by zero which results in ZeroDivisionError at runtime.

def divide_num(num1, num2):
    return num1/num2

divide_num(10, 0)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 4, in <module>
    divide_num(10, 0)
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 2, in divide_num
    return num1/num2
ZeroDivisionError: division by zero

When these types of runtime errors occur in Python code, an exception object is created and raised. If there is no exception handling code to handle it then the error message is displayed that shows the context where the exception happened, in the form of a stack traceback. The exception type (at least in case of built-in exception) is printed as part of the message.

Python 3 exception hierarchy

In Python all exceptions are represented as classes and derive from BaseException class. The class hierarchy for built-in exceptions in Python is as follows.

Python 3 exception hierarchy

As you can see from the Python Exception hierarchy all built-in, non-system-exiting exceptions are derived from Exception class. All user-defined exceptions should also be derived from this class.

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program.

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program. Warnings unlike exceptions are not fatal and don't terminate the program. Warning is the base class for warning categories.

Python exception handling

While writing robust code we should provide checks for the eventuality where program may fail at run time because of some condition like zero division, file not found, type error.

Default behavior for handling such exceptions in Python is for the interpreter to print the full stack traceback, that includes the exception type (at least in case of built-in exception) and error message, and then terminate the program.

By providing your own exception handling you can display an appropriate message and then continue with the program rather than terminating the program.

To handle exception in Python you can use the following procedure-

  1. Use try block to enclose code that might throw an exception.
  2. Use except block to handle the raised exceptions.
  3. Use finally clause to perform clean up like closing the opened file.

Together these three keywords constitute the Python exception handling. General form of exception handling in Python is as follows.

try: 
 try suite
               
except Exception1:
 handler suite
except Exception2:
 handler suite
else:
 else suite
finally: 
 finally suite

There can be more than one except block, based on the type of the exception raised appropriate except block is executed. Read more in this post- Python Exception Handling - try,except,finally

If no exception is raised then the statements in the else block are executed.

Statements inside the finally block are always executed whether an exception is raised or not.

Python exception handling example

def divide_num(num1, num2):
    try:
        print('Result-',num1/num2)
    except ZeroDivisionError:
        print('Division by zero')
        print('Zero is not a valid argument here')
    else:
        print('in else block')

divide_num(10, 0)
divide_num(10, 2)

Output

Division by zero
Zero is not a valid argument here
Result- 5.0
in else block

As you can see in the first call to function 0 is passed as divisor which results in ‘ZeroDivisionError’ so the except block handles that exception. Since the exception handling is done so the program doesn’t terminate and the second function is also executed. This time there is no error so an optional else block is executed.

Apart from try, except and finally other keywords used in Python exception handling are-

  • raise- Allows you to force a specified exception to occur.
  • assert- The assert statement enables you to verify if a certain condition is true or not. If it not true then it raises AssertionError.

Python built-in exceptions

Python language has several built-in exceptions, some of the important one are listed below.

Exception Class Description
ArithmeticError The base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError.
AssertionError Raised when an assert statement fails.
EOFError Raised when the input() function hits an end-of-file condition (EOF) without reading any data.
ImportError Raised when the import statement has troubles trying to load a module.
IndexError Raised when a sequence subscript is out of range.
KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys.
OverflowError Raised when the result of an arithmetic operation is too large to be represented.
RuntimeError Raised when an error is detected that doesn’t fall in any of the other categories.
SyntaxError Raised when the parser encounters a syntax error.
IndentationError Base class for syntax errors related to incorrect indentation. This is a subclass of SyntaxError.
SystemError Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope.
TypeError Raised when an operation or function is applied to an object of inappropriate type.
ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.
FileNotFoundError Raised when a file or directory is requested but doesn’t exist.

That's all for this topic Python Exception Handling Tutorial. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. User-defined Exceptions in Python
  2. self in Python
  3. Python return Statement With Examples
  4. Constructor in Python - __init__() function
  5. Nonlocal Keyword in Python With Examples

You may also like -

  1. Changing String Case in Python
  2. Class And Object in Python
  3. Python Generator, Generator Expression, Yield Statement
  4. Convert String to int in Python
  5. What Are JVM, JRE And JDK in Java
  6. Java Concurrency Interview Questions And Answers
  7. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  8. How to Handle Missing And Under Replicated Blocks in HDFS