PythonServer Side ProgrammingProgramming
Beyond Basic Programming - Intermediate Python
Most Popular
36 Lectures 3 hours
Mohammad Nauman
More Detail
Practical Machine Learning using Python
Best Seller
91 Lectures 23.5 hours
MANAS DASGUPTA
More Detail
Practical Data Science using Python
22 Lectures 6 hours
MANAS DASGUPTA
More Detail
IOError Exception
It is an error raised when an input/output operation fails, such as the print statement or the open[] function when trying to open a file that does not exist. It is also raised for operating system-related errors.
If the given code is written in a try block, it raises an input/output exception, which is handled in the except block as shown given below
Example
import sys def whatever[]: try: f = open [ "foo.txt", 'r' ] except IOError, e: print e print sys.exc_type whatever[]
Output
[Errno 2] No such file or directory: 'foo.txt'
Rajendra Dharmkar
Updated on 12-Jun-2020 08:08:32
- Related Questions & Answers
- How to catch KeyError Exception in Python?
- How to catch ArithmeticError Exception in Python?
- How to catch OverflowError Exception in Python?
- How to catch IndexError Exception in Python?
- How to catch NameError Exception in Python?
- How to catch EOFError Exception in Python?
- How to catch SyntaxError Exception in Python?
- How to catch IndentationError Exception in python?
- How to catch TypeError Exception in Python?
- How to catch EnvironmentError Exception in Python?
- How to catch LookupError Exception in Python?
- How to catch ZeroDivisionError Exception in Python?
- How to catch FloatingPointError Exception in Python?
- How to catch StandardError Exception in Python?
- How to catch StopIteration Exception in Python?
Previous Page Print Page Next Page
Advertisements
Exceptions in Python
Python has many built-in exceptions that are raised when your program encounters an error [something in the program goes wrong].
When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.
For example, let us consider a program where
we have a function A
that calls function B
, which in turn calls function C
. If an exception occurs in function C
but is not handled in C
, the exception passes to B
and then to A
.
If never handled, an error message is displayed and our program comes to a sudden unexpected halt.
Catching Exceptions in Python
In Python, exceptions
can be handled using a try
statement.
The critical operation which can raise an exception is placed inside the try
clause. The code that handles the exceptions is written in the except
clause.
We can thus choose what operations to perform once we have caught the exception. Here is a simple example.
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print["The entry is", entry]
r = 1/int[entry]
break
except:
print["Oops!", sys.exc_info[][0], "occurred."]
print["Next entry."]
print[]
print["The reciprocal of", entry, "is", r]
Output
The entry is a Oops! occurred. Next entry. The entry is 0 Oops! occured. Next entry. The entry is 2 The reciprocal of 2 is 0.5
In this program, we loop through the values of the randomList list. As previously mentioned, the portion that can
cause an exception is placed inside the try
block.
If no exception occurs, the except
block is skipped and normal flow continues[for last value]. But if any exception occurs, it is caught by the except
block [first and second values].
Here, we print the name of the exception using the exc_info[]
function inside sys
module. We can see that a
causes ValueError
and 0
causes ZeroDivisionError
.
Since every exception in Python inherits from the base Exception
class, we
can also perform the above task in the following way:
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print["The entry is", entry]
r = 1/int[entry]
break
except Exception as e:
print["Oops!", e.__class__, "occurred."]
print["Next entry."]
print[]
print["The reciprocal of", entry, "is", r]
This program has the same output as the above program.
Catching Specific Exceptions in Python
In the above example, we did not mention any specific exception in the except
clause.
This is not a good programming practice as it will catch all exceptions and handle every case in the same way. We can specify which exceptions an except
clause should catch.
A try
clause can have any
number of except
clauses to handle different exceptions, however, only one will be executed in case an exception occurs.
We can use a tuple of values to specify multiple exceptions in an except clause. Here is an example pseudo code.
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except [TypeError, ZeroDivisionError]:
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass
Raising Exceptions in Python
In Python programming, exceptions are raised when errors occur at runtime. We can also manually raise exceptions using the raise
keyword.
We can optionally pass values to the exception to clarify why that exception was raised.
>>> raise KeyboardInterrupt
Traceback [most recent call last]:
...
KeyboardInterrupt
>>> raise MemoryError["This is an argument"]
Traceback [most recent call last]:
...
MemoryError: This is an argument
>>> try:
... a = int[input["Enter a positive integer: "]]
... if a