Python Exception Handling – Try And Except Fundamentals


Python Exception handling is very critical for creating robust and stable applications. And it encourages programmers to write clean, readable and error-free code.

You’ll all accept that each one of us may leave errors while writing programmable code. After all, we are humans. Sometimes we make a syntactical mistake or provide a wrong input to the program. Also, a program may fail if it needs a network resource which is not available. Even it may face out of memory and similar errors.

Some of these errors may cause the program to terminate abruptly. Since none of us want a program to behave nasty, so we make arrangements to handle such situations. With the help of Python exception handling, we can manage the above issues and avoid intermittent failures of our code. The most common way to do it is by creating a python try-except block.

First of all, we have to understand the difference between an error and the exception. Consequently, we’ll teach you the essentials of Python exception handling.

The Difference Between An Error And The Exception.

What Is Error?

The error is something that goes wrong in the program, e.g. like a syntactical error.

It occurs at compile time. Let’s see an example.

Example of an error in Python.

The errors also occur at runtime, and we know them as exceptions. An exception is an event which occurs during the execution of a program and disrupts the normal flow of the program’s instructions.
What Is Exception?

In general, when a Python script encounters an error situation that it can’t cope with, it raises an exception.

When a Python script raises an exception, it creates an exception object. Usually, the script handles the exception immediately. If it doesn’t do so, then the program will terminate and print a traceback to the error along with its whereabouts.

Example of an exception in Python.

How To Use Python Try/Except Clause?

Like many languages, in Python, a try statement is available for exception handling.

In every try block, there is a piece of code which can raise an exception. And the code that handles the exception, we place in the except clause.

Following is the syntax of a Python try-except-else> block.

Python try except syntax.

Checklist To Handle An Exception In Python.

Here is a checklist for using the Python try statement effectively.

  • A single try statement can have multiple except statements depending on the requirement. In this case, a try block contains statements that can throw different types of exceptions.
  • We can also add a generic except clause which can handle all possible types of exceptions.
  • We can even include an else clause after the except clause. The code in the else block will execute if the code in the try block doesn’t raise any exception.

Python Exception Handling # Example-1.

Let’s take a sample code to understand the use of Python try-except.

Python try except example-1.

The above code produces the following output.

Python Exception Handling # Example-2.

Let’s take another example in which we are trying to open a file in the READ mode. Then, we’ll perform a WRITE operation on it. Upon execution, it’ll throw the following exception.

Python try except example-2.

The above code produces the following output.

How To Define Except Clause With No Exceptions?

Defining except clause with no exceptions enables it to handle all types of exceptions. However, neither it’s a good programming practice nor does anyone recommend it.

It is because that such a Python try-except block can handle all types of exceptions. But it’ll not help the programmer to find which type of exception caused the issue.

If you still want to use it, then refer the following code.

Python Exception Handling # Example-3.

Python try-except clause with no exception.

How To Use Except Clause With Multiple Exceptions?

We can define multiple exceptions with the same except clause. It means that if the Python interpreter finds a matching exception, then it’ll execute the code written under the except clause.

In short, when we define except clause in this way, we expect the same piece of code to throw different exceptions. Also, we want to take the same action in each case.

Please refer the below example.

Python Exception Handling # Example-4.

Python try-except clause with multiple exceptions.

How To Use Python Try-Finally Clause?

With try block, we also have the option to define the “finally” block. This clause allows defining statements that we want to execute, no matters whether the try block has raised an exception or not.

This feature usually comes in the picture while releasing external resources.

Here is the coding snippet for help.

Python Exception Handling # Example-5.

One very important point is that we can either define an “except” or a “finally” clause with every try block. You can’t club these together. Also, you shouldn’t use the “else” clause along with a “finally” clause.

Let’s take an example to get more clarity.

If the exception doesn’t occur, then you’ll see the following output.

Python Exception Handling # Example-6.

Suppose we open the file in the READ mode and then try to perform a write operation on it. In such a situation, below code will help to handle the exception.

In this case, the interpreter will raise an exception and the following output will get displayed.

When some code causes an exception in a try block, the execution immediately passes to the “finally” block. After all the statements in the “finally” block get executed, the exception resumes to the “except” block for execution. But there must present a next higher layer of the “try-except” statement.

How To Raise An Exception And Provide Arguments?

We can forcefully raise an exception using the raise keyword. We can also optionally pass values to the exception and specify why this exception should occur. Here is the syntax for calling the “raise” method.


  • The exception is the name of the exception.
  • The “args” is optional and represents the value of the exception argument.
  • The final argument, traceback, is also optional and if present, is the traceback object used for the exception.

Let’s take an example to clarify this.

Python Exception Handling # Example-7.

User-Defined Exceptions.

How To Define A Custom Exception In Python?

We can add user-defined exceptions by creating a new class in Python. The trick here is to derive the custom exception class from the base exception class. Most of the built-in exceptions use the same technique to enforce their exceptions.

Create An Exception Class In Python.

In the above code snippet, you can see that we have created a user-defined exception class, the “UserDefinedError“. It is using the base Exception class as the parent. Hence, the new user-defined exception class will raise exceptions as any other exception class does i.e. by calling the “raise” statement with an optional error message.

Let’s take an example.

Python Exception Handling # Example-8.

In this example, we will show how to raise an user-defined exception and catch errors in a program. Also, in the sample code, we will ask the user to enter an alphabet again and again until he enters the stored alphabet only.

For help, the program provides a hint to the user so that he can figure out the correct alphabet. Also, he can check whether his guess is greater or less than the stored alphabet.

Example-8# Run With Multiple Tests Data.

Let’s test this program by supplying different inputs.

Thus you can see that we have defined a base class called Error here in this program. The two exceptions (“InputTooSmallError” and “InputTooLargeError“) that are raised by our program are derived from this class. It’s the standard way to define user-defined exceptions in Python programming.

List Of Python Built-In Exceptions.

Exception Cause of Error
AirthmeticError For errors in numeric calculation.
AssertionError If the assert statement fails.
AttributeError When an attribute assignment or the reference fails.
EOFError If there is no input or the file pointer is at EOF.
Exception It is the base class for all exceptions.
EnvironmentError For errors that occur outside the Python environment.
FloatingPointError When floating point operation fails.
GeneratorExit If a generator’s <close()> method gets called.
ImportError When the imported module is not available.
IOError If an input/output operation fails.
IndexError When the index of a sequence is out of range.
KeyError If the specified key is not available in the dictionary.
KeyboardInterrupt When the user hits an interrupt key (Ctrl+c or delete).
MemoryError If an operation runs out of memory.
NameError When a variable is not available in local or global scope.
NotImplementedError If an abstract method isn’t available.
OSError When a system operation fails.
OverflowError If the result of an arithmetic operation exceeds the range.
ReferenceError When a weak reference proxy accesses a garbage collected reference.
RuntimeError If the generated error doesn’t fall under any category.
StandardError It is a base class for all built-in exceptions except <StopIteration> and <SystemExit>.
StopIteration The <next()> function has no further item to be returned.
SyntaxError For errors in Python syntax.
IndentationError When indentation is not proper.
TabError For inconsistent tabs and spaces.
SystemError When interpreter detects an internal error.
SystemExit The <sys.exit()> function raises it.
TypeError When a function is using an object of the incorrect type.
UnboundLocalError If the code using an unassigned reference gets executed.
UnicodeError For a Unicode encoding or decoding error.
ValueError When a function receives invalid values.
ZeroDivisionError If the second operand of division or modulo operation is zero.

Summary – Python Try And Except Fundamentals.

We most of the time aims to pick a topic that can help in your work. Also, we intend to teach you skills that matter the most in your job profile. That’s why we did this post on using Python Fundamentals Tutorial try/except statements.

It would be great to hear from you if this post helped you in learning Python. So do let us know about your experience.

Also, you can submit a request for any topic of your choice. We’ll include it in our plan and add to the priority list.


If you have any queries then feel free to comment down below
And If you liked the post, then please don’t miss to share it with friends and on social media
Thank you for reading.


Python – The Complete Course for Beginners

Python and Django Full Stack Web Developer Bootcamp

The Python Mega Course: Build 10 Python Applications 


Please enter your comment!
Please enter your name here