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.
('Yeah ! Your answer is :', 1)
Code 1 : There is an exception so only except clause will run.
Sorry ! You are dividing by zero
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 firstname.lastname@example.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.
- Python | Index of Non-Zero elements in Python list
- Python | Merge Python key values to list
- Python | Convert list to Python array
- Important differences between Python 2.x and Python 3.x with examples
- Reading Python File-Like Objects from C | Python
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Visualizing O(n) using Python
- Any & All in Python
- Python vs PHP
- max() and min() in Python
- Python Set | pop()