If you are a Python developer, you might have noticed that as soon as you encounter an error in Python, the program terminates. Errors in Python can be of two types - Syntax Errors and Exceptions. Syntax errors are simple to locate and deal with. However, dealing with logical errors or Exceptions is somewhat difficult, and this is exactly what this article will try to cover.

Try-Except in Python

The most common way to deal with exceptions in Python is by using the try-except block, which can be used to handle exceptions. The general syntax of a try-except clause in Python is -

try:
  <do something>
except Exception:
  <handle the error>

1. Try - The try block allows you to test the blocks of code where the exception is most likely to occur. In case it finds or raises an exception, the control jumps straight into the Except block.

2. Except - If an exception is raised inside the try block, the except block is executed. It is necessary to specify an except block, always with a try block. This is where you specify what to do when an exception occurs.

Two other types of blocks can be used to assist the exception handling process using try-except blocks.

  1. Else: If there were no exceptions raised inside the try block, you can use the else block to define codes that need to be executed in such a case.
  2. Finally: Irrespective of the fact whether an exception was raised inside a try block or not, it always executes the code that you mention inside the final block.

Let’s understand how the try-except blocks work.

The code that you mention between the try and except clauses, that is inside the try block, is first executed. If it finds no breaks or exceptions inside the try block, then the code inside the except blocks does not run. If you have mentioned else and finally blocks, then the codes inside these blocks will get executed.

If an error or exception is raised inside the try block, then the flow jumps straight inside the except block, and the codes that you specify inside it get executed. The remaining code inside the try block does not get executed, in such a case. If the except clause does not handle the exception, it takes the flow to the outer try block. This means that you can have nested try blocks as well. If the outer try block also does not handle the exception, then the execution stops.

However, if the exception is handled inside the except block, then the code mentioned inside the finally block, if there is one, gets executed. Please note that each try block can have over one else blocks and the one that handles first will execute. 

Hence, the hierarchy of specifying except blocks should be in such a way that the most specific except blocks should come first, followed by the most generic ones. You will understand this in greater detail with examples later on in this tutorial.

Become a Certified Expert in AWS, Azure and GCP

Caltech Cloud Computing BootcampExplore Program
Become a Certified Expert in AWS, Azure and GCP

Why Should You Use the Try-Except Blocks?

There might be several unknown or unexpected errors that can occur in your program during runtimes. The try-except-else-finally blocks help you to avoid such problems. For example, the Python coding style called ‘Look Before You Leap’ generally leads to race conditions. The try-except blocks can help you a lot here. 

There might be certain critical code snippets that might depend on data that might become outdated at a certain point in time. Some examples include “os.path.exists”, “queue.empty”, etc. which might fail in certain conditions. Hence, it’s a wise decision to include such code snippets inside a try-except block.

Before you start exploring the try-except way of handling exceptions in greater detail in Python, you must know what exactly exceptions are and what are their types. 

Exceptions in Python

Exception handling in Python allows developers to control the flow of the program, even if the program ceases to run. Exceptions are considered to be errors that occur during program executions. As discussed earlier, if there is a syntax error while executing a Python script, it will end abruptly, which is bad for the programmers and end-users.

However, if there is a runtime exception in Python, it shows you what is the type of exception. It can do this because it has several in-built exceptions which, when occurs, can be determined by Python and display the exact information using tracebacks. If you don’t deal with these exceptions, the program crashes. 

All the exceptions in Python are inherited from the BaseException class. Let’s discuss a few common in-built exceptions in Python that you might encounter frequently while writing Python scripts.

Common Exceptions in Python

There are a plethora of in-built exceptions in Python, and they are all listed in the Python official Documentation. However, you can use the following command to get a list of all of them.

>>> dir(locals()['__builtins__'])

The above command gives the following list of in-built exceptions as an output.

CommonExceptionsinPython

Let’s discuss a few of them.

1. TypeError

This is a common type of error in Python which is raised when you try to invoke a function or an operation on a data-type or object that is inappropriate or not supported. 

Let’s understand this with the help of an example.

dividend = int(input())

divisor = input()

result = dividend/divisor 

print("The result is: {}".format(result))

In the above program, you are taking the inputs from the user for dividend and the divisor variables. You know that for the division to take place, both the variables should be of integer, double, or float data types. You have to typecast the dividend to an integer, however, you have taken the divisor input as a string. This is why you will get a TypeError because the division operator is not able to operate on string data types. 

TypeError.

2. ZeroDivisionError

This is another common type of logical error in Python. If you try to divide any number by zero, Python invokes a ZeroDivisionError exception, halts the program, and prints the traceback. Let’s check it out.

print(43/0)

ZeroDivisionError.

Become a Data Scientist With Real-World Experience

Data Scientist Master’s ProgramExplore Program
Become a Data Scientist With Real-World Experience

3. ValueError

This usually occurs when you provide an argument of the right type, but the inappropriate value to a function or an operation. Let’s check out the example below.

dividend = int(input())

divisor = int(input())

result = dividend/divisor 

print("The result is: {}".format(result))

Here, you have to typecast both the dividend and divisor variables. Now, if you provide an alphanumeric value as an input for any of these variables, then Python won’t be able to perform the typecasting. Hence, even though the data types are correct, the value is wrong. That’s when Python throws the ValueError exception.

ValueError

4. AttributeError

If you try to reference or assign an attribute that doesn’t exist, then Python throws the AttributeError exception. Let’s check out the example below.

import math

result = math.sqr(int(input()))

print(result)

The Math module in Python has tons of functions and attributes that help you to perform computations. One such function is sqrt. It helps to calculate the square root of a number. But in this program, you have incorrectly mentioned the name of the sqrt attribute of the Math module. This is why Python will throw an AttributeError exception here.

AttributeError

In all the above examples, you might have noticed something called tracebacks. Tracebacks in Python are generated when an exception occurs. Traceback contains the message regarding the error telling us which exceptions were raised, what all happened before they were raised, the lines of codes that exactly caused the errors, all with the help of a call stack that occurs internally to execute codes.

Exception Handling With Try-Except Block

Let’s see an example where you can use try-except blocks to handle exceptions. 

x = int(input("Please enter a number: "))

try:

   result = 10/x

except Exception as error:

   print("The following error occured - ", error)

   exit(0)

print("The result is - ", result)

In the above example, you have defined a variable called x which is initialized by an input integer. You have used a try block inside which you have performed a simple division where the dividend is 10 and divisor is the variable x that you took as input. Inside the exception block, you have printed the error that was caught inside the try block and exited the program. In the end, if no exception occurs, then the result gets printed.

Try-ExceptBlock

If you input a non-zero number, then no exception occurs and the program executes perfectly. However, if the input divisor is 0, the division operation inside the try block gives ZeroDivisionError which is caught by the except block where you have mentioned the handling code to print the error.

Using the Else Clause With Try-Except

As discussed earlier, you can use the Else clause along with the Try-Except block in Python. In case no exception gets raised inside the try block, the control jumps straight to the else block, and the code inside it gets executed. Let’s check it out with an example.

x = int(input("Please enter a number: "))

try:

   result = 10/x

except Exception as error:

   print("The following error occured - ", error)

   exit(0)

else:

   print("The program was executed successfully.")

   print("The result is - ", result) 

print("Thanks!")

Try-Except

You can see that when you took the input as a non-zero number, no exceptions were raised inside the try block and the else got executed. However, when you took 0 as an input for the divisor, the ZeroDivisionError was raised and the else block did not execute.

Using Finally Clause With Try-Except-Else

The Finally block can be used to mention those snippets of codes that have to be executed irrespective of the fact whether an exception occurs or not.

x = int(input("Please enter a number: "))

try:

   result = 10/x

except Exception as error:

   print("The following error occured - ", error)

   exit(0)

else:

   print("The result is - ", result)

   print("The program was executed successfully.")

finally:

   print("Thanks!")

In the above program, it doesn't matter whether the input divisor is zero or not, the code inside the finally block will execute. 

Try-Except-Else 

You can see that the print statement inside the finally block always gets executed.

The Ultimate Ticket to Top Data Science Job Roles

Post Graduate Program In Data ScienceExplore Now
The Ultimate Ticket to Top Data Science Job Roles

Using Multiple Except Clauses With One Try block

With a single try block, you can specify multiple except blocks to handle specific exceptions. The most commonly followed hierarchy is to first handle specific exceptions such TypeError, ArithmeticError, ValueError, etc. and at last, you handle general error using Exception. 

When an exception is raised inside the try block, the control flow of the program starts looking for except clauses sequentially, and hence, if it does not find a specific except block which can handle it, it will choose the general ones at the end. This is usually the best practice.

Let’s understand this with the help of the following example.

x = int(input("Please enter a number: "))

try:

   result = 10/x

except TypeError as error1:

   print("The following error occured - ", error1)

   exit(0)

except ValueError as error2:

   print("The following error occured - ", error2)

   exit(0)

except ZeroDivisionError as error3:

   print("The following error occured - ", error3)

   exit(0)

except Exception as error4:

   print("The following error occured - ", error4)

   exit(0)

else:

   print("The result is - ", result)

   print("The program was executed successfully.")

finally:

   print("Thanks!")

In the above program, you have defined 4 except blocks among which the first three of them handle specific exceptions and the last one handle the generic exception. In this case, a ZeroDivisionError is thrown by the try block if you input the dividend as 0. The control first checks for the exception handling by the first check block which takes TypeError as an argument that does not match. Then, it goes to the 2nd and 3rd blocks. Since it matches with the third block, it stops there and executes the code inside it.

oneTryblock.

Handle More Than One Exceptions With a Single Except Clause

Instead of specifying multiple except blocks for a single try block, you can use a single except clause to specify multiple exceptions directly. It is generally used when you suspect that the program inside the try block might raise different types of exceptions and you want to perform the same action for all of them. Let’s consider the following example.

def get_result(number, index):

   numbers = [5, 15, 0]  

   position = numbers[index]

   return number/position

number = int(input("Please enter the dividend: "))

index = int(input("Please enter the index of divisor in array [5, 15, 0]: "))

try:

   result = get_result(number, index)

   print("The result is: ", result)

except (ZeroDivisionError, IndexError) as error:

   print(error)

Here, you have a function that takes a dividend and an index value as input. Inside the function, you have an array of three numbers, one of which will be used as a divisor. You return the final result of the division. Then, you take as input the dividend and the index of the array whose corresponding element you want to use as the divisor.

If you input an index value that is greater than the length of the array, then an IndexError must be thrown. And when you enter 2 as an index value, then 0 will be used as the divisor and ZeroDivisionError must be thrown. Let’s check the output in both scenarios.

singleexceptclause

You can see that it automatically decides which exception to be used based on the exception thrown by the try block.

Raise an Exception

It is also possible to raise your exceptions using the raise method in Python. It is very useful to create custom user-defined exceptions and also during the sanity checks. The general syntax of raise in Python is - 

>>> raise [ExceptionName[(*args: Object)]]

Let’s try to use it inside a program. 

dividend = int(input())

divisor = int(input())

if dividend < 0:

   raise Exception("Oops! Please enter a positive number")

if divisor==0:

   raise ZeroDivisionError

if not type(dividend) is int:

   raise TypeError

print("The result is: ", (dividend/divisor))

In the above program, you have defined three raises to raise different types of exceptions. The first one raises a general exception, the second raises a ZeroDivisionError, and the last one raises a TypeError. Let’s check out the output.

RaiseanException

You can see those appropriate exceptions are caught and thrown each time.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Wrapping Up!

In this comprehensive tutorial on try-except in Python, you saw the difference between syntax errors and exceptions, what are the different types of exceptions along with their examples, you explored why it is vital to handle them, and you can do so using try-catch blocks.

This article also discussed the use of else and finally clauses along with the try-except blocks. You witnessed how to use multiple except clauses with a single try block, and handle multiple exceptions using a single except clause. 

Finally, you saw how to raise your custom exceptions using the raise method which can further be used to create user-defined exceptions.

We hope that with the help of this comprehensive tutorial, you will now be able to get hands-on with try-except in Python.

If you are looking for a more comprehensive understanding of the python programming language, Simplilearn’s Python Certification Course would be ideal for you. This program is tailored-made for individuals looking to master python and gain the practical work-ready knowledge they need to become a professional in the field. From data operations to shell scripting, conditional statements, and Django, you will learn all the fundamental topics associated with python from top-class practitioners in the field today.

Nevertheless, if you have any queries or feedback for us on this try except in python article, do feel free to share them with us in the comments section of this article. Our subject matter experts will review and reply to them at the earliest opportunity.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 30 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449