try() is used in Error and Exception Handling
There are two kinds of errors :
- Syntax Error : Also known as Parsing Errors, most basic. Arise when the Python parser is unable to understand a line of code.
- Exception : Errors which are detected during execution. eg – ZeroDivisionError.
List of Exception Errors :
- IOError : if file can’t be opened
- KeyboardInterrupt : when an unrequired key is pressed by the user
- ValueError : when 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
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?
- First try clause is executed i.e. the code between try and except clause.
- If there is no exception, then only try clause will run, except clause is finished.
- If any exception occured, 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 left unhandled, then the execution stops.
- A try statement can have more than one except clause
Code 1 : No exception, so try clause will run.
# 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)
Code 1 : There is an exception so only except clause will run.
# 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
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.