Open In App

Python Try Except

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
134 Likes
Like
Report

In Python, errors and exceptions can interrupt the execution of program. Python provides try and except blocks to handle situations like this. In case an error occurs in try-block, Python stops executing try block and jumps to exception block. These blocks let you handle the errors without crashing the program.

Python
try:
    # Code that may raise an exception
    x = 3 / 0
    print(x)
except:
    # exception occurs, if code under try throws error
    print("An exception occurred.")

Output
An exception occurred.

Try Except in Python

Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.

Syntax:

try:
# Some Code
except:
# Executed if error in the
# try block

Why do we need try-except

  • Prevents crashes caused by runtime errors.
  • Handles specific exceptions like division by zero, file not found, etc.
  • Improves code reliability and error tolerance.
  • Allows custom error messages and fallback logic.
  • Essential for robust, debuggable applications.

How try() works? 

  • First, the try clause is executed i.e. the code between try.
  • If there is no exception, then only the try clause will run, except clause is finished.
  • If any exception occurs, the try clause will be skipped and except clause will run.
  • If any exception occurs, but the except clause within the code doesn't handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.
  • A try statement can have more than one except clause

Some of the common Exception Errors are : 

  • IOError: if the file can't be opened
  • KeyboardInterrupt: when an unrequired key is pressed by the user
  • ValueError: when the built-in function receives a wrong argument
  • EOFError: if End-Of-File is hit without reading any data
  • ImportError: if it is unable to find the module

Example 1: No exception, so the try clause will run. 
 

Python
# Python code to illustrate
# working of try() 
def divide(x, y):
    try:
        # Floor Division : Gives only Fractional Part as Answer
        result = x // y
        print("Yeah ! Your answer is :", result)
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")

# Look at parameters and note the working of Program
divide(3, 2)

Output
Yeah ! Your answer is : 1

Example 2: There is an exception so only except clause will run. 

Python
# Python code to illustrate
# working of try() 
def divide(x, y):
    try:
        # Floor Division : Gives only Fractional Part as Answer
        result = x // y
        print("Yeah ! Your answer is :", result)
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")

# Look at parameters and note the working of Program
divide(3, 0)

Output
Sorry ! You are dividing by zero 

Example 3:  The other way of writing except statement, is shown below and in this way, it only accepts exceptions that you're meant to catch or you can check which error is occurring.

Python
# code
def divide(x, y):
    try:
        # Floor Division : Gives only Fractional Part as Answer
        result = x // y
        print("Yeah ! Your answer is :", result)
    except Exception as e:
       # By this way we can know about the type of error occurring
        print("The error is: ",e)

        
divide(3, "GFG") 
divide(3,0) 

Output
The error is:  unsupported operand type(s) for //: 'int' and 'str'
The error is:  integer division or modulo by zero

Else Clause

In Python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.

Syntax:

try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception

Example:

Python
# Program to depict else clause with try-except
 
# Function which returns a/b
def AbyB(a , b):
    try:
        c = ((a+b) // (a-b))
    except ZeroDivisionError:
        print ("a/b result in 0")
    else:
        print (c)
 
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

Output
-5.0
a/b result in 0

Finally Keyword in Python

Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after the normal termination of the try block or after the try block terminates due to some exceptions.

Syntax:

try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code .....(always executed)

Python
# Python program to demonstrate finally 
# No exception Exception raised in try block 
try: 
    k = 5//0 # raises divide by zero exception. 
    print(k) 
   
# handles zerodivision exception     
except ZeroDivisionError:    
    print("Can't divide by zero") 
       
finally: 
    # this block is always executed  
    # regardless of exception generation. 
    print('This is always executed')  

Output
Can't divide by zero
This is always executed

Nested Try-Except Blocks in Python

In Python, you can nest try-except blocks to handle exceptions at multiple levels. This is useful when different parts of the code may raise different types of exceptions and need separate handling.

Example:

Python
def divide_and_access(a, b):
    try:
        result = a // b
        print("Result:", result)
        
        try:
            lst = [1, 2, 3]
            print("Accessing index 5:", lst[5])  # This will raise IndexError
        except IndexError:
            print("Handled inner IndexError: Invalid index access.")
    
    except ZeroDivisionError:
        print("Handled outer ZeroDivisionError: Cannot divide by zero.")

    finally:
        print("Outer finally block always runs.")

# Testing both types of exceptions
divide_and_access(6, 2)
print("---")
divide_and_access(6, 0)

Output

Result: 3
Handled inner IndexError: Invalid index access.
Outer finally block always runs.
---
Handled outer ZeroDivisionError: Cannot divide by zero.
Outer finally block always runs.

Related Articles: 

Suggested Quiz
12 Questions

What is an exception in Python?

  • A

    A syntax error

  • B

    A runtime error

  • C

    A logical error

  • D

    A compile-time error

Explanation:

Exceptions in Python are runtime errors that occur when something goes wrong during the execution of a program.

How can you handle exceptions in Python?

  • A

    Using if-else statements

  • B

    Using try-except blocks

  • C

    Using switch-case statements

  • D

    Using for loops

Explanation:

Try-except blocks are used to catch and handle exceptions in Python.

What is the purpose of the finally block in exception handling?

  • A

    To define a block of code that will be executed if an exception occurs

  • B

    To specify the code to be executed regardless of whether an exception occurs or not
     

  • C

    To catch and handle specific exceptions
     

  • D

    To raise a custom exception
     

Explanation:

The finally block contains code that will be executed no matter what, whether an exception occurs or not.

Which of the following statements is used to raise a custom exception in Python?

  • A

    throw

  • B

    raise 

  • C

    catch

  • D

    except

Explanation:

The raise statement is used to raise a specific exception manually.

What will be the output of the following code?

try:
   result = 10 / 0
except ZeroDivisionError:
   result = "Infinity"

print(result)
 

  • A

    10

  • B

    "Infinity"

  • C

    ZeroDivisionError

  • D

    None

Explanation:

The code catches the ZeroDivisionError and assigns "Infinity" to the result variable.

What is the purpose of the else block in exception handling?

  • A

    To handle exceptions

  • B

    To specify code that will be executed if no exceptions are raised

  • C

    To define custom exceptions

  • D

    To skip the execution of the block if an exception occurs

Explanation:

The else block contains code that is executed when no exceptions are raised in the try block.

How can you catch multiple exceptions in a single except block?

  • A

    Using a comma-separated list of exceptions

  • B

    Using nested try-except blocks

  • C

    By defining a custom exception

  • D

    Using the catch keyword

Explanation:

You can catch multiple exceptions by separating them with commas in a single except block.

Will the finally block execute if an exception occurs and is not handled by any except block?

  • A

    It doesn't execute

  • B

    It executes before the exception is raised

  • C

    It executes after try/except blocks

  • D

    It executes only if the exception is caught

Explanation:

The finally block always runs after try and except, even if an exception is not handled.

What is the purpose of the raise statement in Python?

  • A

     To raise an arbitrary exception

  • B

    To terminate the program

  • C

    To catch an exception

  • D

    To ignore an exception

Explanation:

The raise statement is used to raise a specific exception manually.

What will happen if an exception is raised but not caught in a Python program?

  • A

    The program will terminate abruptly

  • B

    The program will continue to execute without any impact

  • C

    The program will print an error message and continue

  • D

    The program will prompt the user to handle the exception

Explanation:

If an exception is not caught, it leads to an abrupt termination of the program.

 How can you re-raise an exception in Python?

  • A

    Using the retry statement

  • B

    Using the throw statement

  • C

    Using the raise statement without any arguments

  • D

    Using the rethrow keyword

Explanation:

The raise statement without any arguments re-raises the last exception.

Which of the following is the correct syntax to catch an exception and store its details in a variable?

  • A

    except Exception e:

  • B

    except Exception, e:

  • C

    catch Exception as e:

  • D

    except Exception as e

Explanation:

In Python, except Exception as e is used to catch an exception and bind the exception instance to the variable e, allowing access to its details.

Quiz Completed Successfully
Your Score :   2/12
Accuracy :  0%
Login to View Explanation
1/12 1/12 < Previous Next >

Article Tags :

Explore