Jython exceptions
Regardless of how much care a programmer takes in designing and testing his or her code, unexpected errors, or exceptions, can occur. Jython provides excellent support for recovering from these errors,
Exceptions are generally subclasses of the Jython
type exceptions.Exception or the Java class
java.lang.Exception. Most Jython exception
names end in "Error" (such as IOError or
IndexError) or
"Warning." Java exceptions end in either "Error" (for
critical exceptions) or "Exception" (for generally
recoverable exceptions). For more information see The Jython exception hierarchy
or the Python Library Reference (see Resources for a link).
The Jython exception hierarchy
Here is Jython's principle exception hierarchy subset.
- 1 Exception
- 1.1 SystemExit
- 1.2 StopIteration
- 1.3 StandardError
- 1.3.1 KeyboardInterrupt
- 1.3.2 ImportError
- 1.3.3 EnvironmentError
- 1.3.3.1 IOError
- 1.3.3.2 OSError
- 1.3.4 EOFError
- 1.3.5 RuntimeError
- 1.3.5.1 NotImplementedError
- 1.3.6 NameError
- 1.3.6.1 UnboundLocalError
- 1.3.7 AttributeError
- 1.3.8 SyntaxError
- 1.3.8.1 IndentationError
- 1.3.8.2 TabError
- 1.3.9 TypeError
- 1.3.10 AssertionError
- 1.3.11 LookupError
- 1.3.11.1 IndexError
- 1.3.11.2 KeyError
- 1.3.12 ArithmeticError
- 1.3.12.1 OverflowError
- 1.3.12.2 ZeroDivisionError
- 1.3.12.3 FloatingPointError
- 1.3.13 ValueError
- 1.3.14 ReferenceError
- 1.3.15 SystemError
- 1.3.16 MemoryError
- 2 Warning
- 2.1 UserWarning
- 2.2 DeprecationWarning
- 2.3 PendingDeprecationWarning
- 2.4 SyntaxWarning
- 2.5 OverflowWarning
- 2.6 RuntimeWarning
- 2.7 FutureWarning
This hierarchy is a subset of the Python Library Reference (see Resources). These exceptions may be subclassed.
Like C++ and the Java language, Jython supports exception
handlers. These handlers are defined by the
try-except-else statement, which has the following
form:
try: statement
except type, var: statement
:
else: statement
-- or --
try:
block
except type, var:
block
:
else:
block
|
The except clause may be repeated with different
type values. If so, the exceptions either must not
overlap hierarchically (that is, be siblings) or they must be ordered
from child to root exceptions. The optional type value
is an exception type (either a subclass of
exceptions.Exception or
java.lang.Throwable). If type is missing,
then the except clause catches all Jython and Java
exceptions. The optional var value receives the actual
exception object. If var is missing, then the exception
object is not directly accessible. The else clause is
optional. It is executed only if no exception occurs.
If an exception occurs in the try clause, the clause
is exited and the first matching except clause (if any) is entered. If no exception matches, the block containing the try-except-else is exited and the exception is re-raised.
If an exception is raised in the except or else clause, the
clause will exit and the new exception will be processed in
the containing block.
Accessing exception information
To access information about an exception, you may use
the value provided in the except clause as described previously or the sys.exc_info function. For example, you can use the following function, in which type is the class of the exception, value is the exception object (use str(value) to get the message), and traceback is the execution trace back, which is a linked list of execution stack frames.
import sys
:
try:
:
except:
type, value, traceback = sys.exc_info()
|
More details on the exceptions and trace backs is available in the Python Reference Manual (see Resources).
Like C++ and the Java language, Jython supports an additional
construct, try-finally, which makes it easy to do
required cleanup activities such as closing open files,
releasing resources, etc. Any code in the finally
clause is guaranteed to be executed once the try
clause is entered, even if it is exited via a return
statement (see The return statement) or an exception.
The try-finally statement has the following forms:
try: statement
finally: statement
-- or --
try:
block
finally:
block
|
Note that try-except-else statements may nest in
try-finally statements and vice versa.
Here is an example of using both try-except and
try-finally statements together. We'll talk more about
Jython file I/O in Part 2 of this tutorial.
def readfile (name):
"return the lines in a file or None if the file cannot be read"
try:
file = open(name, 'r') # access the file
try:
return file.readlines()
finally:
file.close() # ensure file is closed
except IOError, ioe: # report the error
print "Exception -", ioe
:
# prints Exception - File not found - nofile (...)
# then None
print readfile("nofile")
# prints a list of the lines in the file
print readfile("realfile")
|
Exceptions are generated by called functions or built-in services.
You can also generate one by using the raise statement.
The raise statement has the following forms:
raise exception
-- or --
raise exception_class {, message}
-- or --
raise
|
Below are some example raise statements.
| Example | Comment(s) |
raise
| Re-raise the current exception; used in an except block to regenerate the exception |
raise IOError
| Create and raise an IOError with no message |
raise anIOError
| Re-raise an existing IOError object |
raise IOError, "End of File"
| Create and raise an IOError with a explanatory message |
from java import io
raise io.IOException, "End of File"
| Create and raise a Java exception with a explanatory message |

