jython and java exceptions

Alan Kennedy alanmk at hotmail.com
Sat Aug 7 08:43:10 EDT 2004


[Jan Gregor]
>  I found that jython catches exact java exceptions, not their
> subclasses. Is there some way to get around this limitation (or error) ?

Hmm, not sure what you mean here. Consider the following code

#################
from java.io import FileInputStream
from java.io import IOException
from java.io import FileNotFoundException; # Subclasses IOException

dud_file_name = "does_not_exist.txt"

def open_file(filename):
   return FileInputStream(filename)

# For this function, we expect the FileNotFoundException clause
# to be executed, because it is listed first, and matches the
# exception precisely

def catch_subclass():
   try:
     f = open_file(dud_file_name)
     f.close()
   except FileNotFoundException, fnfx:
     print "Caught expected FileNotFoundException: %s" % str(fnfx)
   except IOException, iox:
     print "Error: should not have reached IOException clause"

# For this function, we expect the IOException clause to be
# executed, because it is listed first, and matches the exception,
# because FileNotFoundException is a subclass of IOException

def catch_superclass():
   try:
     f = open_file(dud_file_name)
     f.close()
   except IOException, iox:
     print "Caught expected IOException: %s" % str(iox)
   except FileNotFoundException, fnfx:
     print "Error: should not have reached FileNotFoundException clause"

if __name__ == "__main__":
   catch_subclass()
   catch_superclass()
########################

AFAICT, the above code demonstrates the correct behaviour for java 
exception handling in jython, and contradicts your statements above.

Perhaps you can post a code sample that shows what you mean?

>  My program has class representing database source and specialed classes
> for particulars databases. Now there are two options - to include
> exception (subclasses of SQLException) for every db in except (so
> all drivers has to be present) or to move methods to subclasses.

You should be able to catch all exceptions using code like this

try:
   # database operations
except java.sql.SqlException:
   # This will catch all SQLExceptions and subclasses.

-- 
alan kennedy
------------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/contact/alan



More information about the Python-list mailing list