Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Exception Handling in Python

In this blog, we will learn exception handling in python. Let’s have a look at the content discussed below i.e. what we are learning in this article

What is Exception Handling in Python?

An error that occurs during program execution is an exception. To prevent your program from crashing, Python creates an exception when a program is executing. Exceptions in the Python programming language can be automatically caused by errors or can be manually triggered and intercepted by your code.

The exception shows that even though the event might happen, it does so rarely. The caller function receives the exception when the method is unable to handle it. Eventually, the program ends abruptly when an exception is thrown outside of the main function.

Common Examples of Exception:

  • Division by Zero
  • Accessing a file that does not exist.
  • Addition of two incompatible types
  • Trying to access a nonexistent index of a sequence
  • Removing the table from the disconnected database server.
  • ATM withdrawal of more than the available amount

Why should you use Exceptions?

Here are the reasons for using exceptions in Python:

  • Exception handling in python allows you to separate error-handling code from normal code.
  • An exception is a Python object which represents an error.
  • As with code comments, exceptions help you to remind yourself of what the program expects.
  • It clarifies the code and enhances readability.
  • Allows you to stimulate consequences as the error-handling takes place in one place and in one manner.
  • An exception is a convenient method for handling error messages.
  • In Python, you can raise an exception in the program by using the raise exception method.
  • Raising an exception helps you to break the current code execution and returns the exception back to expection until it is handled.
  • Processing exceptions for components that can’t handle them directly.

Rules of Exceptions

Here are some essential rules of Python exception handling:

  • Exceptions must be class objects
  • For class exceptions, you can use a try statement with an except clause which mentions a particular class.
  • Even if a statement or expression is syntactically correct, it may display an error when an attempt is made to execute it.
  • Errors found during execution are called exceptions, and they are not unconditionally fatal.

Python Exception Handling Mechanism

Exception handling in python is managed by the following 3 keywords:

  • try
  • catch
  • finally
  • Throw or raise

Python Try Statement

A try statement consists of the keyword try, a colon (:), and a group of code that may contain exceptions. It contains a clause or clauses.
If no exceptions arise during the try statement’s execution, the interpreter ignores the try statement’s specified exception handlers.

A try suite expires if an exception occurs within it, and program control then passes to the matching except for the handler that came after the try suite.


The catch Statement

The sort of exception that it is likely to catch is one that is taken one argument at a time by catch blocks. These justifications might be anything from a particular sort of exception that can be changed to a general category of exceptions.
Norms for the catch block:

  • You can define a catch block by using the keyword catch
  • The catch Exception parameter is always enclosed in parentheses
  • It always represents the type of exception that the catch block handles.
  • An exception handling code is written between two {} curly braces.
  • You can place multiple catch block within a single try block.
  • You can use a catch block only after the try block.
  • All the catch block should be ordered from subclass to superclass exception.


catch (ArrayIndexOutOfBoundsException e) {
System.err.printin("Caught first " + e.getMessage()); } catch (IOException e) {
System.err.printin("Caught second " + e.getMessage());

Finally Statement in Python

Whether or not there is an exception, the finally block always runs. You may write a block of code that comes after a try-catch block by using the final keyword.

A clause is optional, to sum up. It aims to provide cleanup procedures that must be followed in all circumstances.

    raise KeyboardInterrupt
    print 'welcome, world!'


Welcome, world!

Finally, the clause is executed before the try statement.

Raise Statement in Python

The raise statement specifies an argument that initializes the exception object. Here, a comma follows the exception name, and argument or tuple of the argument that follows the comma.

raise [Exception [, args [, traceback]]]

In this syntax, the argument is optional, and at the time of execution, the exception argument value is always none.

Error Type Description
ArithmeticError ArithmeticError act as a base class for all arithmetic exceptions. It is raised for errors in arithmetic operations.
ImportError ImportError is raised when you are trying to import a module which does not present. This kind of exception occurs if you have made typing mistake in the module name or the module which is not present in the standard path.
IndexError An IndexErroris raised when you try to refer a sequence which is out of range.
KeyError When a specific key is not found in a dictionary, a KeyError exception is raised.
NameError A NameError is raised when a name is referred to in code which never exists in the local or global namespace.
ValueError Value error is raised when a function or built-in operation receives an argument that may be of the correct type but does not have a suitable value.
EOFerror This kind of error raises when one of the built-in functions (input() or raw_input()) reaches an EOF condition without reading any data.
ZeroDivisonError This type of error is raised when division or module by zero takes place for all numeric types.
IOError- This kind of error is raised when an input/output operation fails.
syntaxError SyntaxErrors are raised when there is an error in Python syntax.
IndentationError This error is raised when indentation is not properly defined

This blog gives a brief explanation of exception handling in python in which we have discussed the definition, Rules, Examples of exception handling in python, we hope this article will help you to better understanding of the topic exception handling in python.

Other Python Programs
Python program to reverse a number
Python program for heap sort
Python program to check armstrong number
Python program to check leap year
Python program to convert celsius to fahrenheit
Python program to find factorial of a number
Python program to reverse a linked list
Python Program to find the middle of a linked list using only one traversal
Python Program to Add Two Numbers
Python Program to Check Palindrome Number
Python Program to Print the Fibonacci Series
Python Loop Program
Anagram Program in Python
Fizzbuzz Program in Python
String Programs in Python
List Program in Python
Prime Number Program in Python

Leave a Reply

Your email address will not be published. Required fields are marked *