Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Difference between Syntax Error and Exceptions
2.1.
Syntax Error
2.2.
Exceptions
3.
Try and Except Statement – Catching Exceptions
4.
Catching Specific Exception
5.
Try with Else Clause
6.
Finally Keyword in Python
7.
Raising Exception
8.
Frequently Asked Questions
9.
Key Takeaways
Last Updated: Mar 27, 2024

Catching an Exception in Python (try-except)

Author Sanjana Yadav
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Software programs do not always work flawlessly. Even after extensive debugging and several levels of testing, apps continue to fail. Bad data, faulty network connectivity, damaged databases, memory pressures, and unexpected user inputs can all cause an application to fail. An exception happens when such an event occurs, and the program cannot resume its regular flow.

Exceptions in Python programs can occur for various causes. If they aren't handled properly, they can cause the program to crash, resulting in data loss or, worse, data corruption. As a Python programmer, you must consider various exception scenarios and include error management in your code.

Python, fortunately, includes a sophisticated error handling system. Python applications may detect the error type at run time using structured exception handling and a collection of pre-defined exceptions. Taking a different path, using default settings, or urging for accurate input are examples of these activities.

Also See, Divmod in Python and Convert String to List Python.

Difference between Syntax Error and Exceptions

Syntax Error

This error occurs due to incorrect code syntax. The program is terminated as a result of this.

Example

Here's an example with a syntax error (notice the missing colon after the parenthesized "if" condition)

x = 70
y = 90
if (x < y)
    print('x is less than y')
z = 130
print (z)

Output

File "main.py", line 3
    if (x < y)
             ^
SyntaxError: invalid syntax

The interpreter detects the error and displays the line number. 

Exceptions

An exception is thrown when a program is syntactically accurate, yet the code produces an error. This error does not stop the program from running, but it does interrupt the typical flow of the program.

Example

num = 10000
t = num / 0
print(t)

Output

File "main.py", line 2, in <module>
t = num / 0
ZeroDivisionError: division by zero

In this example, the ZeroDivisionError was thrown as we were trying to divide by 0.

Similar to ZeroDivisionError, there are several in-built-exceptions in python, such as

ModuleNotFoundError, ImportError, MemoryError, OSError, SystemError, etc.

A complete list of exceptions may be found in the Python Documentation.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

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")

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

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")

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

# 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)

Output

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

 

You can try it on online python compiler.

Finally Keyword in Python

Finally is a keyword in python, which is always run after the try and except blocks. The finally block is always executed after the try block has terminated normally or after the try block has terminated due to an exception.

Syntax

try:
    # Some Code 
except:
    # optional block
    # Handling of exception (if required)
else:
    # executes if there is no exception
finally:
    # Some code(always executed)

Example

try:
    e = 5//0
    print(e)
except:
    print("Can't divide by zero")
finally:
    print('This statement is always executed')

Output

Can't divide by zero
This statement 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).

try:
    raise NameError("Hi peeps!!")
except NameError:
    print ("Exception occurred")
    raise # To determine whether the exception was raised or not

Output

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

Must Read, python packages

Frequently Asked Questions

  1. What does it mean to catch an exception Python?
    In Python, the try and except block captures and handles errors. As previously demonstrated, when syntactically valid code encounters an issue, Python will throw an exception error. If this exception error is not handled, the application will crash. The except clause specifies how your program handles exceptions.
     
  2. Does catch exception catch all exceptions?
    Yes. Because it is the base of all exceptions, it will catch any exception.
     
  3. What happens if the try-catch block is not used?
    If no exception occurs in the try block, the catch blocks are ignored. 
     
  4. Can we write code in a catch block?
    No, we cannot insert statements between the try, catch, and finally blocks, which comprise a single unit. We can construct statements like try with catch block, try with multiple catch blocks, try with finally block, and try with catch and finally blocks, but no code or statements may be written between these combinations.

Key Takeaways

  • Cheers if you reached here! In this blog, we learned about Exception Handling in Python. 
  • We have covered the basic difference between syntax errors and exceptions.
  • We have also seen different combinations of try, except, else and finally keywords.
  • Further, we learned to raise an exception.

On the other hand, learning never ceases, and there is always more to learn. So, keep learning and keep growing, ninjas!

Check out this article - Quicksort Python

Check out the Top 100 SQL Problems to get hands-on experience with frequently asked interview questions and land your dream job.

Good luck with your preparation!

Previous article
Raising an Exception
Next article
User-defined Exception in Python
Live masterclass