The Wayback Machine - https://web.archive.org/web/20210207145329/https://www.geeksforgeeks.org/python-try-except/amp/

Python Try Except

try() is used in Error and Exception Handling
There are two kinds of errors :

List of Exception Errors :

Now, here comes the task to handle these errors within our code in Python. So here we need try-except statements.

Basic Syntax : 
 try:
    // Code
 except:
    // Code

How try() works?

Code 1 : No exception, so try clause will run.



filter_none

edit
close

play_arrow

link
brightness_4
code

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

Output :

('Yeah ! Your answer is :', 1)

Code 1 : There is an exception so only except clause will run.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

Output :

Sorry ! You are dividing by zero

Related Articles:

This article is contributed by Mohit Gupta_OMG 😀. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




Article Tags :