
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How can I write a try/except block that catches all Python exceptions?
It is a general thumb rule that though you can catch all exceptions using code like below, you shouldn’t:
try: #do_something() except: print "Exception Caught!"
However, this will also catch exceptions like KeyboardInterrupt we may not be interested in. Unless you re-raise the exception right away – we will not be able to catch the exceptions:
try: f = open('file.txt') s = f.readline() i = int(s.strip()) except IOError as (errno, strerror): print "I/O error({0}): {1}".format(errno, strerror) except ValueError: print "Could not convert data to an integer." except: print "Unexpected error:", sys.exc_info()[0] raise
We get output like the following, if the file.txt is not available in the same folder as the script.
I/O error(2): No such file or directory
- Related Articles
- How to catch multiple exceptions in one line (except block) in Python?
- Can we declare a try catch block within another try catch block in Java?
- try and except in Python
- try and except in Python Program
- Can we write code in try/catch block in JSP as well?
- Can we have a try block without a catch block in Java?\n
- How to raise an exception in one except block and catch it in a later except block in Python?
- Explain try, except and finally statements in Python.
- Explain Try, Except and Else statement in Python.
- Can a try block have multiple catch blocks in Java?
- How to use the ‘except’ clause with multiple exceptions in Python?
- How to use the ‘except clause’ with No Exceptions in Python?
- How can I remove all elements except the first one using jQuery?
- Is it necessary that a try block should be followed by a catch block in Java?
- Can we define a try block with multiple catch blocks in Java?

Advertisements