Exceptional Handling
Exceptional Handling
EXCEPTIONAL HANDLING
EXCEPTIONAL HANDLING
ERRORS
) Missing
2. Semantic Errors
What is an exception?
For Example
Exception Handling
When you run the program in Listing 11.3 or Listing 11.4, what
happens if the user enters a file or an URL that does not exist? The
program would be aborted and raises an error. For example, if you
run Listing 11.3 with an incorrect input, the program reports an IO
error as shown below:
c:\pybook\python CountEachLetter.py
Enter a filename: newinput.txt
Traceback (most recent call last):
File "CountEachLetter.py", line 23, in <module>
main()
File "CountEachLetter.py", line 4, in main
Infile = open(filename, "r"> # Open the file
IOError: [Errno 2] No such file or directory: 'newinput.txt'
14
The try ... except Clause
try:
<body>
except <ExceptionType>:
<handler>
15
The try ... except Clause
try:
<body>
except <ExceptionType1>:
<handler1>
...
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>
16
Raising Exceptions
You learned how to write the code to handle exceptions in the
preceding section. Where does an exception come from? How is
an exception created? Exceptions are objects and objects are
created from classes. An exception is raised from a function.
When a function detects an error, it can create an object of an
appropriate exception class and raise the object, using the
following syntax:
17
Processing Exceptions Using Exception Objects
You can access the exception object in the except
clause.
try
<body>
except ExceptionType as ex:
<handler>
18
Defining Custom Exception Classes
BaseException
Exception
StandardError
ZeroDivionError IndentationError
IOError OSError IndexError KeyError
Handling Exceptions
Handling Exceptions
For Example
Handling Exceptions
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.
Some common exceptions
KeyboardInterrupt
Raised when the user hits the interrupt 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
CLASS TEST
CLASS TEST