MarsDevs Introduces You to Exception Handling in Python

Published on:
November 3, 2022

In this article, MarsDevs will present to you what Exceptions are, why they are needed, how exceptions can be raised manually, and how to handle exceptions.

Introduction to Exception

When we try to execute the code, errors might occur. These errors interrupt the normal flow of the program. The Python interpreter often fails to deal with these errors and therefore raises an exception.

Exceptions can be defined as errors found during execution. Exceptions are raised whenever an error occurs in the program. Error handling is needed to prevent a program that ends abruptly. 

If exceptions are not handled, the program may go into a crash state. As a developer, it is our responsibility to handle exceptions that occur, such that the program will execute in any case.

Consider the following example,

There is an unhandled exception in the above code.

Exception Handling in Python

Exceptions can be referred to as unexpected behavior of an application or program. It is also known as some interruption in the flow of code. Whatever it is, it is the developer's duty to handle all these exceptions.Python, like other programming languages, is equipped with provisions for handling exceptions. One way is to use try and except blocks.

The try block allows us to write the code which is likely to have errors or exceptions. If any exception occurs then the except block is triggered. In except block developers can control the flow of the program. Thus, helped in handling the exceptions. 

You can write any important code inside the try block. The exception block is triggered whenever an expected or unexpected exception occurs (except clause can detect any number of exceptions raised inside the try clause).

In order to get a clear understanding of try & except, let’s consider an example.

The Python interpreter raises an exception as an object that contains information about the exception message and type. Furthermore, every exception type in Python inherits from the base class Exception.

Consider the following example,

Common Exceptions in Python

Now, let us discuss some common exceptions in Python. Furthermore, all built-in exceptions in Python are inherited from the Exception class.

Name of the Exception 

  • Exception - It is the base class for all exceptions.
  • StopIteration - It is raised when while iterating, the next() method of an iterator doesn’t point to any object. 
  • ArithmeticError - It is the base class for all errors that occur for numeric calculation.
  • OverflowError - It is raised when a calculation exceeds the maximum limit for a numeric type.
  • ZeroDivisionError - It is raised when division or modulo by zero takes place for all numeric types.
  • AssertionError - It is raised in case of failure of the Assert statement.
  • AttributeError - It is raised in case of failure of attribute reference or assignment.
  • EOFError - It is raised when there is no input from either the raw_input() or input() function and the end of the file is reached.
  • ImportError - It is raised when an import statement fails.
  • NameError - It is raised when an identifier is not found in the local or global namespace.
  • SyntaxError - It is raised when there is an error in Python syntax.
  • IdentationError - It is raised when indentation is not done properly.
  • TypeError - It is raised when a function or operation is applied to an object of an incorrect type.
  • ValueType - It is raised when a function gets an argument of correct type but improper value.
  • RuntimeError - It is raised when an error does not fall under any other category.
  • NotImplementedError - It is raised by abstract methods.
  • OSError - It is raised when a system operation causes a system-related error.
  • KeyError - It is raised when a key is not found in a dictionary.
  • MemoryError - It is raised when an operation runs out of memory.
  • UnicodeError - It is raised when a function or operation is applied to an object of an incorrect type.
  • KeyboardInterrupt - It is raised when the user hits the interrupt key (Ctrl+c or delete).

To check all exceptions, visit python’s official documentation on exceptions.

Consider the following examples,

Catching Specific Exceptions in Python

As discussed earlier, whenever an exception is raised in the try block, the exception clause will handle it. But it is a good practice to handle or catch all specific types of exceptions, for this we can use multiple except blocks.

Consider the following example,

In the above example, we have handled 2 exceptions (using 2 except blocks) based on the input entered by the user. If q is not zero, the output will be 1. If q is 0, the output will be 2. If we want to catch both the exceptions in one except block then the code can be rewritten as

Raising Custom Exceptions

Although exceptions are automatically raised during runtime when an error occurs, we can also create custom exceptions using the raise keyword. Any exception that a developer can raise if he needs to break the flow of a program under specific circumstances can be called a custom exception.

Consider the following example,

But, if you pass a string by first name, it will print accordingly.

Use of Try - Except - Else

Sometimes we need to run the program only when there is no exception, in that case, the else keyword is used with the try clause.

If an exception is raised then the except block will be triggered, otherwise the else block will be triggered.

Consider the following example,

In the above example, since the value of num2 is greater than 0, no ZeroDivisionError is raised and hence the flow of code moves to the else block and the message is no exception.

Consider another example, 

In this example, since num2 is 0, the flow of code goes through the except block and we get the message exception.

Try clause with Finally

The finally keyword is used when we want a piece of code to be executed, regardless of whether exceptions are raised or not. The finally keyword comes after the try-except or else block.

Consider the following example,

In the example above, we try to access the fifth element of the list, so in addition to handling this error and giving the list index out of bounds exception, the code in the finally block is printed despite the exception.

Consider another example,

Note that the else block will always be triggered when there is no exception raised and the finally block will always be triggered regardless of any exceptions or not.


Similar Posts