Table of contents
1.
Introduction 
2.
Try and Except in Python
2.1.
Syntax
3.
How try() works? 
4.
Try and Except Statement – Catching Exceptions
4.1.
Python
5.
Catching Specific Exception
5.1.
Python
6.
Try with Else Clause
6.1.
Python
6.2.
Example 1
6.3.
Example 2
7.
Finally Keyword in Python
7.1.
Syntax
7.2.
Example 
8.
Raising Exception
8.1.
Python
9.
Frequently Asked Questions
9.1.
When should we use try/except Python?
9.2.
Can we use try without Except?
9.3.
Is if-else faster than try-except?
10.
Conclusion
Last Updated: Aug 21, 2025
Easy

Try and Except in Python

Author Shivam Verma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

In Python, the try except statement is used to catch and handle errors. An exception is an object representing an error, and if not managed, it can crash the program. Using try except Python ensures smooth execution by handling such exceptions effectively.

Here is a list of common exceptions that a standard Python program can throw.

  • ZeroDivisionError: It occurs when a number is divided by zero.
  • ValueError: Occurs when the built-in function receives a wrong argument.
  • IndentationError: It occurs if an incorrect indentation is given.
  • EOFError: It occurs when End-Of-File is hit without reading any data.
  • IOError: It occurs when the file can not be opened.
  • ImportError: It occurs when the module is not found.

Try and Except in Python

If a python program contains suspicious code that may throw the exception, we must use the Try and Except statements to handle this exception. We use the try block to check for errors in code. The code inside the try block will run if the program contains no errors. On the other hand, the code in the except block will run whenever the program encounters an error in the try block before it.

 

Syntax

try:
    # Block of code
except:
    # Executed if an error in the try block

Let us look at how the different blocks in the above syntax work.

  • The try clause, the code between the try and except clauses, is first executed.
  • Only the try clause will be executed if there is no exception, except clause is skipped.
  • If an exception occurs, the try clause is skipped, and the except clause is executed instead.
  • There can be several except clauses in a try statement.

How try() works? 

  • Try block: Executes the code that might raise an exception.
  • Except block: Catches and handles the specific exception if it occurs.
  • If no exception occurs, the except block is skipped.
  • You can specify multiple exception types or use a general exception handler.

Try and Except Statement – Catching Exceptions

In Python, exceptions are caught and handled using try and except statements. The try clause contains statements that can raise exceptions, whereas the except clause contains statements that handle the exception.

try: 
#program code
except: 
      #exception handling code
#program code

The program flow enters the "try" block. 

Control is passed to the code in the "except" block if an exception occurs. The error handling code in the "except" block is determined by the sort of error you expect the code in the "try" block may encounter.

Example

  • Python

Python

arr = [1, 2, 3, 4, 5]
try:
   print ("Third element in the array = %d" %(arr[2]))
   print ("Sixth element in the array = %d" %(arr[5]))
except:
   print ("Some error occurred")
You can also try this code with Online Python Compiler
Run Code

Output

Third element in the array = 3
Some error occurred

In the example above, the statements that potentially produce an error are placed inside the try statement (second print statement in our case). The second print statement attempts to access the array's sixth element, which is not there, resulting in an exception. The except statement then catches this exception.

Catching Specific Exception

There can be more than one except clause in a try statement to provide handlers for distinct exceptions. Please keep in mind that only one handler will be used.

The common syntax for adding specific exceptions is

try:
    # statement(s)
except:
    # statement(s)
except:
    # statement(s)

Example

Example to handle multiple errors with one except handler

  • Python

Python

def func(num1):
   if num1 < 4:
       num2 = num1/(num1-3)
   print("Value of num2 = ", num2)
try:
   func(3)
except:
   print("ZeroDivisionError Occurred and Handled")  
try:
   func(5)
except:
   print("NameError Occurred and Handled")
You can also try this code with Online Python Compiler
Run Code

Output

ZeroDivisionError Occurred and Handled
NameError Occurred and Handled

This happens because when python tries to access the value of num2, NumError occurs.

Try with Else Clause

In some cases, you may wish to run a specific block of code if the code block inside try ran without problems. You can use the optional else keyword with the try statement in these situations.

The else clause must be present after all the except clauses.

If the try clause does not throw an exception, the code moves to the else block.

Example

  • Python

Python

# program to print the reciprocal of odd numbers
try:
   a = int(input("Enter a number: "))
   assert a % 2 != 0
except:
   print("Even number!")
else:
   reciprocal = 1/a
   print(reciprocal)
You can also try this code with Online Python Compiler
Run Code

Output

Enter a number: 2
Even number!
Enter a number: 5
0.2

 

You can try it on online python compiler.

Example 1

def division(a,b):
    try:
        res=a//b
        print("The answer is :", res)
    except ZeroDivisionError:
        print("Can not divide with zero")
division(14,3)
You can also try this code with Online Python Compiler
Run Code

Output 

The answer is : 4

In the above code, there is no exception, so the try clause will run. 

Example 2

def division(a,b):
    try:
        res=a//b
        print("The answer is :", res)
    except ZeroDivisionError:
        print("Can not divide with zero")
division(14,0)
You can also try this code with Online Python Compiler
Run Code

Output 

Can not divide with zero

In the above code, there is an exception, so only except clause will run.

Finally Keyword in Python

The statement 'finally' is available in Python, and it is always executed after the try and except blocks. The final block is always executed after the try block has terminated normally or due to some exceptions.

Syntax

try:
    # Block of code
except:
    # Executed if an error in the try block
else:
    # Executes if no exception
finally:
    # block of code    
    # this will always be executed 

Example 

def division(a,b):
    try:
        res=a//b
        print("The answer is:", res)
    except ZeroDivisionError:
        print("Can not divide with zero")
    finally:
        print('This is always executed') 
division(14,0)
You can also try this code with Online Python Compiler
Run Code

Output

Can not divide with zero
This is always executed

 

Raising Exception

The raise statement enables the programmer to compel the occurrence of a specified exception. The exception to be raised is indicated by the sole argument in raise. This must be either an exception instance or a class of exceptions (a class that derives from Exception).

  • Python

Python

try:
   raise NameError("Hi peeps!!")
except NameError:
   print ("Exception occurred")
   raise # To determine whether the exception was raised or not
You can also try this code with Online Python Compiler
Run Code

Output

File "main.py", line 2, in <module>
    raise NameError("Hi peeps!!")
NameError: Hi peeps!!

You can try it on online python compiler.

Frequently Asked Questions

When should we use try/except Python?

When we have a code block to execute that will run correctly sometimes and incorrectly other times, depending on conditions we can't predict when writing the code, we should use try/except Python.
 

Can we use try without Except?

We can't have a try block without an except block, so the only thing is to try to ignore the raised exception and specify the pass statement in the except block.
 

Is if-else faster than try-except?

The exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means that if an exception is thrown, the exception handler will take longer than if version of the code.

Conclusion

In this article, we have extensively discussed try and except in the Python programming language. We also discussed the syntax and example of the try and except statement in Python.

Recommended Readings:

 

Live masterclass