Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Try and Except in Python
2.1.
Syntax
2.2.
Example 1
2.3.
Example 2
3.
Finally Keyword in Python
3.1.
Syntax
3.2.
Example 
4.
FAQs
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Try and Except in Python

Author Shivam Verma
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction 

In Python, the try and except statement is used to catch and handle exceptions. Before knowing more about try and except in Python, let us understand what the exception is?

In Python, an exception is a Python object that represents an error. Python provides many built-in exceptions that are raised when our program encounters an error. When these exceptions occur, the Python interpreter suspends the current process and passes control to the calling process until the problem is resolved. The program will crash if it is not handled properly.

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.

Recommended Topic, Floor Division in Python and Convert String to List Python.

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.

Read More, leap year program in python

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.

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)

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)

Output 

Can not divide with zero

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

Recommended Topic, Divmod in Python

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

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)

Output

Can not divide with zero
This is always executed

 

You can try it on online python compiler.

Also see, How to Check Python Version in CMD

FAQs

  1. When should we use try/except Python?
    Ans: 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.
     
  2. Can we use try without Except?
    Ans: 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.
     
  3. Is if-else faster than try-except?
    Ans: 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.

We hope that this blog has helped you enhance your knowledge regarding try and except. If you would like to learn more, check out our article on Arrays. You can read our Python language articles by clicking Python Archives

Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Assertionerror Python
Next article
Raising an Exception to another Exception
Live masterclass