Python Files

Python Exception Handling

Software programs and applications do not always work flawlessly. When we write a program, we can make mistakes that cause errors when we run it. In Python, you may encounter two types of mistakes: syntax errors and exceptions. Before enabling the rest of the program to run, you may wish to test a specific block of code to ensure it works properly. Python try except blocks allow you to test your code and handle exceptions if they occur. Finally and else statements can also be used to run additional code based on the outcome of the try…except block. In this article, we’ll go through how to use the Python try except concept.

Exceptions in Python

An exception is defined as an unexpected condition in a program that causes the program’s flow to be interrupted.

When the Python interpreter attempts to execute invalid code, it throws an exception, and if the exception is not handled, it disturbs the regular flow of the program’s instructions and outputs a traceback. Exceptions are a form of error in which the code has the correct syntax but contains a fault. There are many different types of exceptions, but some of the most prevalent are: ArithmeticError, ImportError, ZeroDivisionError, NameError, and TypeError.

As Python developers, we must consider various exception circumstances and incorporate error management into your code. Python, fortunately, includes a sophisticated error handling system. Python applications may determine the error type at run time and act accordingly by using structured exception handling and a collection of pre-defined exceptions. These actions can include adopting a different route, using default settings, or urging for accurate input.

Catching Exceptions in Python

For exception handling, most current programming languages employ a mechanism known as “try-catch.” Exceptions in Python can be managed with a try statement. This prevents the program from exiting abruptly in the event of an error. The basic form in Python is the “Python try except.” The try clause contains the critical operation that can cause an exception. The except clause contains the code that handles exceptions.

The try block allows you to check for mistakes in a block of code. The except block allows you to handle errors with a custom response.

The try-except syntax block appears to be as follows:

                    

try:
       # There can be error code in this block
except :
       # Do this to handle exception;
       # executed if the try block throws an error

So how exactly does the Python try except clause works?

  • The try clause is run first, followed by the code between the try and except clauses.
  • If there is no exception, only the try clause will be executed, unless the clause is completed.
  • And if an exception occurs, the try clause is bypassed and the except clause is executed.
  • If an exception occurs but the except clause within the code does not handle it, the exception is passed on to the outer try statements. If the exception is not handled, the execution is terminated.
  • There can be more than one unless a clause in a try statement.

Let us look at a basic try-except clause program below,

                    

def divide(x, y):
      try:
             res = x / y
             print('Your answer is :', res)
      except ZeroDivisionError:
             print('Sorry! You are dividing by zero')

divide(5, 0)

Output

                    

Sorry! You are dividing by zero

Another example is as follows,

                    

# import module sys to get the type of exception
import sys
my_list = ['A', 0, 10]

for i in my_list:
    try:
        print("The entry is", i)
        resi = 1/int(i)
        break
    except:
        print('Oops!', sys.exc_info()[0], 'occurred.')
        print()

print('The reciprocal of', i, 'is', resi)

Output

                    

The entry is A
Oops! <class 'ValueError'> occurred.

The entry is 0
Oops! <class 'ZeroDivisionError'> occurred.

The entry is 10
The reciprocal of 10 is 0.1

In this program, we loop through the randomList list’s values. As previously stated, the component that may result in an exception is placed within the try block. If no exceptions occur, the except block is bypassed and normal flow resumes (for last value). However, if an exception occurs, it is handled by the except block (first and second values). Using the exc_info() method from the sys module, we print the name of the exception. We can see that A results in a ValueError and 0 results in a ZeroDivisionError.

Catching Specific Exceptions in Python

In the previous example, no specific exception was mentioned in the unless clause. This is a bad programming technique because it will catch all exceptions and treat every case the same way. We can indicate which exceptions should be caught with an except clause. To trap distinct types of exceptions, you can include numerous “except” blocks in the “try” block. This is beneficial because each “except” block will handle a different type of error.

Example

                    

try:
    num1 = input('Enter 1st number: ')
    num2 = input('Enter 2nd number: ')
    result = (int(num1) * int(num2))/(10 * int(num2))
except ValueError as ve:
    print(ve)
    exit()
except ZeroDivisionError as zde:
    print(zde)
    exit()
except TypeError as te:
    print(te)
    exit()
except:
    print('Unexpected Error!')
    exit()

print(result)

Output

                    

Enter 1st number: 10
Enter 2nd number: 0
division by zero

Enter 1st number: One
Enter 2nd number: Ten
invalid literal for int() with base 10: 'One'

Enter 1st number: 20
Enter 2nd number: 10
2.0

Raising Exceptions in Python

Exceptions are raised in Python programming when faults occur during runtime. The raise clause in Python can be used to forcefully raise an exception. It comes in handy when we need to throw an exception to stop the application from running. We can optionally pass values to the exception to explain why it was raised. The syntax for using the raise statement is as follows.

                    

raise Exception_class,

For example

                    

try: 
     num = int(input('Enter a positive integer: ')) 
     if(num <= 0): 
# we can pass the message in the raise statement 
           raise ValueError('That is a negative number!') 
except ValueError as e: 
     print(e)

Output

                    

Enter a positive integer: -10
That is a negative number!

Python try with else clause

In some cases, you may want to run a specific bit of code if the code block inside try completed without errors. You can utilize the optional else keyword with the try statement in these circumstances. You can also use the else clause on the try-except block in Python, which must come after all the except clauses. If there are no exceptions thrown by the “try” block, the “else” block is executed. The syntax is as follows,

                    

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

Note – If and only if no exception is triggered, the else clause is executed.

Example

                    

def Recp(num):
    try:
         assert num % 2 == 0
    except:
         print('Not an even number!')
    else:
         reciprocal = 1/num
         print(reciprocal)

Recp(5)
Recp(10)
Recp(0)

Output

                    

Not an even number!
0.1
Traceback (most recent call last):
    File "", line 12, in 
    File "", line 7, in Recp
ZeroDivisionError: division by zero

Python try…finally

But what if we want a message to be printed if an error is returned as well as if no error is found? In Python, the try statement can include an optional finally clause. This clause is always executed and is typically used to release external resources. The final block is always run after the try block has terminated normally or after the try block has terminated owing to specific exceptions.

They are less widely utilized because they do not distinguish whether a code has been successfully performed or not. The syntax followed is mentioned below,

                    

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

Example

                    

try:
    div = 5/0 # raises ZeroDivisionError exception.
    print(div)

# handles ZeroDivision exception   
except ZeroDivisionError:  
    print('Cannot divide by Zero')

finally:
    # this block is always executed regardless of exception generation.
    print('This is always executed')

Output

                    

Cannot divide by Zero
This is always executed

Frequently Asked Questions

Q1. What is try except in Python?

For exception handling, most current programming languages employ a mechanism known as “try-catch.” Exceptions in Python can be managed with a try statement. This prevents the program from exiting abruptly in the event of an error. The basic form in Python is the “Python try except.” The try clause contains the critical operation that can cause an exception. The except clause contains the code that handles exceptions.

The try block allows you to check for mistakes in a block of code. The except block allows you to handle errors with a custom response.

The Python try except syntax block appears to be as follows:

                    

try:
      # There can be error code in this block
except :
      # Do this to handle exception;
      # executed if the try block throws an error

Q2. Can I use try without except in Python?

We can’t have a try block without an except block, so the only thing we can do is try to ignore the thrown exception so that the code doesn’t move to the except block and define the pass statement in the except block, as seen before. The pass statement is the same as writing an empty line of code. Finally, we can use the block. Regardless of whether an exception happens or not, code will be executed.

Example

                    

try:
    a = 1/0
except:
    pass
finally:
    print('Result')

Output

Q3. In Python can a try have multiple except?

We can indicate which exceptions should be caught with an except clause. To trap distinct types of exceptions, you can include numerous “except” blocks in the “try” block. This is beneficial because each “except” block will handle a different type of error.

Example

                    

try:
    num1 = input('Enter 1st number: ')
    num2 = input('Enter 2nd number: ')
    result = (int(num1) * int(num2))/(10 * int(num2))
except ValueError as ve:
    print(ve)
    exit()
except ZeroDivisionError as zde:
    print(zde)
    exit()
except TypeError as te:
    print(te)
    exit()
except:
    print('Unexpected Error!')
    exit()

print(result)

Output

                    

Enter 1st number: 10
Enter 2nd number: 0
division by zero

Enter 1st number: One
Enter 2nd number: Ten
invalid literal for int() with base 10: 'One'

Enter 1st number: 20
Enter 2nd number: 10
2.0

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.