What Is An Exception
What Is An Exception
Raising an Exception
You can raise an exception in your own program by using the raise exception
statement.
Raising an exception breaks current code execution and returns the exception
back until it is handled.
Exception Errors
Below is some common exceptions errors in Python:
IOError
If the file cannot be opened.
ImportError
If python cannot find the module
ValueError
Raised when a built-in operation or function receives an argument that has the
right type but an inappropriate value
KeyboardInterrupt
Raised when the user hits the interrup
key (normally Control-C or Delete)
EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data.
except ValueError:
print('Non-numeric data found in the file.')
except ImportError:
print "NO module found"
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
except:
print('An error occurred.')
Exception handling enables you handle errors gracefully and do something meaningful about it.
Like display a message to user if intended file not found. Python handles exception
using try .. except .. block.
Syntax:
try:
except <ExceptionType>:
As you can see in the try block you need to write code that might throw an exception. When an
exception occurs code in the try block is skipped. If there exist a matching exception type
in except clause then it’s handler is executed.
try:
f = open('somefile.txt', 'r')
print(f.read())
f.close()
except IOError:
print('file not found')
Note: The above code is only capable of handling IOError exception. To handle other kind of
exception you need to add more except clause.
A try statement can have more than once except clause, It can also have optional else
and/or finally statement.
try:
<body>
except <ExceptionType1>:
<handler1>
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>
=======================================================
====================
try:
except ZeroDivisionError:
except SyntaxError:
except:
print("Wrong input")
else:
print("No exceptions")
finally:
def enterage(age):
if age < 0:
if age % 2 == 0:
print("age is even")
else:
print("age is odd")
try:
enterage(num)
except ValueError:
except:
print("something is wrong")
Using Exception objects:-
Now you know how to handle exception, in this section we will learn how to access exception
object in exception handler code. You can use the following code to assign exception object to a
variable.
try:
try:
print("Exception:", ex)
class NegativeAgeException(RuntimeError):
self.age = age
if age % 2 == 0:
print("age is even")
else:
print("age is odd")
try:
num = int(input("Enter your age: "))
enterage(num)
except NegativeAgeException:
print("Only positive integers are allowed")
except:
print("something is wrong")
This program will ask the user to enter a number until they guess a stored number correctly.
To help them figure it out, a hint is provided whether their guess is greater than or less than the
stored number.
# define Python user-defined exceptions:
class Error(Exception):
pass
class ValueTooSmallError(Error):
pass
class ValueTooLargeError(Error):
pass
number = 10
while True:
try:
raise ValueTooSmallError
raise ValueTooLargeError
break
except ValueTooSmallError:
print()
except ValueTooLargeError:
print()
A critical operation which can raise exception is placed inside the try clause and the
code that handles exception is written in except clause.
It is up to us, what operations we perform once we have caught the exception. Here is a
simple example.
import sys
randomList = ['a', 0, 2]
try:
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
...
KeyboardInterrupt
...
>>> try:
... if a <= 0:
... print(ve)
...