Python Exception Handling

In this tutorial you will learn:

  • Exception Handling
  • Exception Handling in Python
  • Common Exception classes in Python
  • Throwing an Exception in Python

Exception Handling

Whenever we develop a program most of the time we make small errors that may or may not be noticeable but they can cause the program to crash. It might be a simple logical programming error or some edge cases that we never thought of while developing the program. In any case we need our program not to crash instead show an error message so we can handle it gracefully like by showing a small error prompt or writing error log in a file. One way to handle errors is by using conditional statements but sometimes there are too many conditions that we might not think of during the development phase. So exception handling allow us to handle all the error cases gracefully and not let our program crash.

Exception Handling in Python

Like in all programming languages we can handle exceptions in Python as well and the way to do that is using a simple syntax of try,  except and finally. Let’s look at the examples to see how they are used in Python.

Example:

Simple exception handling.
  1. try:
  2. sum = a + b
  3. except:
  4. print("An exception occurred")

We can also execute different blocks of code for different types of errors.

  1. try:
  2. result = 1/0
  3. except ZeroDivisionError:
  4. print("Result is infinity")
  5. except:
  6. print("Oops error occurred")
Handling exceptions with finally.
  1. try:
  2. result = 1/0
  3. except:
  4. print("Result is infinity")
  5. finally:
  6. print("Please remove 0 from denominator")
Some common exceptions in Python.

Name

Description

Exception

This is the parent class of all exception.

ArithmeticError

This is the parent class of arithmetic errors.

OverflowError

When the result or number exceeds the limit.

ZeroDivisionError

When a number is divided by 0.

EOFError

When end of file is reached without input.

ImportError

This exception occurs when import statement fails.

IOError

This exception occurs when a problem occurs in input output operation or there is some error in operating system.

SyntaxError

This exception occurs when there is an issue in Python syntax.

IndentationError

This exception occurs when there is an indentation issue in Python.

RuntimeError

This exception occurs when no other category of error fits.

Throwing an Exception in Python

We can also throw an exception and handle it in your program. We can do that using the keyword raise which would throw an exception in your program.

  1. number = 10
  2. if number<50:
  3. raise TypeError("Value should be greater than 50")

Add new comment