- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
try and except in Python
To use exception handling in python, we first need to catch the all except clauses.
Python provides, “try” and “except” keywords to catch exceptions. The “try” block code will be executed statement by statement. However, if an exception occurs, the remaining “try” code will not be executed and the except clause will be executed.
try: some_statements_here except: exception_handling
Let’s see above syntax with a very simple example −
try: print("Hello, World!") except: print("This is an error message!")
Above is a very simple example, let’s understand the above concept with another example −
import sys List = ['abc', 0, 2, 4] for item in List: try: print("The List Item is", item) r = 1/int(item) break except: print("Oops!",sys.exc_info(),"occured.") print('\n') print("Next Item from the List is: ") print() print("The reciprocal of",item,"is",r)
The List Item is abc Oops! <class 'ValueError'> occured. Next Item from the List is: The List Item is 0 Oops! <class 'ZeroDivisionError'> occured. Next Item from the List is: The List Item is 2 The reciprocal of 2 is 0.5
In the above program, the loops run until we get (as user input) an integer that has a valid reciprocal. The code which causes an exception to raise is placed within the try block.
In case some exception occurs, it will be caught by the except block. We can test the above program with different exception errors. Below are some of the common exception errors −
Raised in case we cannot open the file.
Raised in case module is missing.
It happened whenever we pass the argument with the correct type but an inappropriate value of a built-in operator or function.
Whenever the user hits the interrupt key (generally control-c)
Exception raised when the built-in functions hit an end-of-file condition (EOF) without reading any data.
- try and except in Python Program
- Explain try, except and finally statements in Python.
- Explain Try, Except and Else statement in Python.
- How can I write a try/except block that catches all Python exceptions?
- Python - Remove all characters except letters and numbers
- The try-finally Clause in Python
- How to raise an exception in one except block and catch it in a later except block in Python?
- Try, catch, throw and throws in Java
- Product of Array Except Self in Python
- What is the difference between 'except Exception as e' and 'except Exception, e' in Python?
- try keyword in C#
- Try-Catch-Finally in C#
- Try-with-resources in Kotlin
- How to match anything except space and new line using Python regular expression?