Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > jython and java exceptions

Reply
Thread Tools

jython and java exceptions

 
 
Jan Gregor
Guest
Posts: n/a
 
      08-04-2004
Hello

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

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.


Jan
 
Reply With Quote
 
 
 
 
Alan Kennedy
Guest
Posts: n/a
 
      08-07-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
 
Reply With Quote
 
 
 
 
Jan Gregor
Guest
Posts: n/a
 
      08-11-2004
Hello
>

I tried it again with SQLException only but my main loop ends with
uncatched com.sybase.jdbc2.jdbc.SybSQLException.
>

This is extract from my code, exception is thrown by self.db.executeSql(iline),


def run (self):
while (1):
gr_mode= 0
iline= Readline.readline(":", 0)
if iline==None:
continue
iline= strip(iline)
if iline=='\q':
try:
Readline.writeHistoryFile(self.rl_history.getName( ))
except:
print ("Error writing history file!")
System.exit(0)
break
if iline=='\gr':
continue
>

Readline.addToHistory(iline)
>

if re.match(r'^\+ ', iline):
gr_mode= 1
iline= strip(iline[2:])
>

try:
type, result= self.db.executeSql(iline)
if result==None:
continue
if type=='resultSet':
self.process(result)
elif type=='table':
if gr_mode:
wnd = swingWnd.SimpleSwing(result.to_html())
wnd.size= (600,600)
wnd.setVisible(1)
else:
self._print_table(result)
elif type=='viewSource' or type=='procSource':
self.println(result)
elif type=='tableDesc':
self._print_table(result)
elif type=='error':
self.println(result)
# except (SQLException, PSQLException, SybSQLException), e:
except java.sql.SQLException, e:
self.println(e.getMessage())
# except:
# pass

Jan
 
Reply With Quote
 
Alan Kennedy
Guest
Posts: n/a
 
      08-11-2004
[Jan Gregor]
> I tried it again with SQLException only but my main loop ends with
> uncatched com.sybase.jdbc2.jdbc.SybSQLException.


Strange indeed. The only explanation I can think of offhand for the
exception not being caught is if com.sybase.jdbc2.jdbc.SybSQLException
is not a subclass of java.sql.SQLException.

Unfortunately, I can't seem to find the javadoc for the Sybase JDBC
driver online (which is poor performance from Sybase).

Try code of the following form to see what the nature of the exception is

import java.lang.Exception
import java.sql.SQLException

try:
# Insert your exception generating code here
except java.lang.Exception, jlx: # Catch every possible java exception
if isinstance(jlx, java.sql.SQLException):
print "Exc %s is subclass of java.sql.SQLException" % jlx.toString()
else:
print "Exc %s != subclass of java.sql.SQLException!" % jlx.toString()

Run that and let us know what the output is.

--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan
 
Reply With Quote
 
Jan Gregor
Guest
Posts: n/a
 
      08-11-2004
There's result - i put aa on input to force error:

Exc com.sybase.jdbc2.jdbc.SybSQLException: Stored procedure 'aa' not
found. Specify owner.objectname or use sp_help to check whether the
object exists (sp_help may produce lots of output).
!= subclass of java.sql.SQLException!


Problem is that SybSQLException IS subclass of SQLException - verified
by Eclipse IDE (type hierarchy). Similar effects were with jdbc driver
for PostgreSQL.

There's result:
Exc org.postgresql.util.PSQLException: ERROR: syntax error at or near
"aa"
!= subclass of java.sql.SQLException!


Jan

 
Reply With Quote
 
Alan Kennedy
Guest
Posts: n/a
 
      08-11-2004
[Jan Gregor]
> There's result - i put aa on input to force error:


What execution environment are you running it in when you have this
problem? A servlet container? Eclipse? From the command line?

I'm beginning to suspect some form of classloader/classpath issue.

> Exc com.sybase.jdbc2.jdbc.SybSQLException: Stored procedure 'aa' not
> found. Specify owner.objectname or use sp_help to check whether the
> object exists (sp_help may produce lots of output).
> != subclass of java.sql.SQLException!


So your jython code finds that the exception raised does not subclass
the base exception it is trying to catch. Which could mean that the
definitions of the base exception class may be different between the
code trying to catch the exception (your jython) and the code trying to
raise it (Sybase jdbc).

Try the following experiments to see if you get behaviour that is different

1. Try this jython

import java.sql

try:
raise java.sql.SQLWarning() # known subclass of SQLException
except java.sql.SQLException:
print "Successfully caught"
else:
print "Big trouble in Little China"

2. Write some similar code to the above in java, raising an SQLWarning
when an object is created, e.g.

TestSubclassExceptions.java <---------->
import java.sql;

public TestSubclassExceptions
{
public TestSubclassExceptions ( )
throws SQLWarning
{
throw new SQLWarning();
}
}
<-------------------------------------->

Making sure that the class definition is on your classpath, instantiate
a TestSubclassExceptions object inside a jython try..catch as in #1, and
see what happens.

3. Write a version of the above class that raises
com.sybase.jdbc2.jdbc.SybSQLException instead. Make sure to run this one
from the command line, so that you know that the jython classloader is
the one loading the class and exception definitions.

If you're running inside some form of "enterprise container", you may be
tripping over a classloader issue, where base classes/exceptions are
being loaded by different classloaders, possibly with different security
settings. Solving these problems is almost always a case of finding the
right library directory to put your jython.jar, etc, in. This can
sometimes require extensive documentation delving.

Final sanity check: are you setting the "python.home" property if/when
you are embedding jython? There are some minor complexities associated
with caching of "compiled" java packages. These can cause odd behaviour
if you are executing your code from two different execution
environments, e.g. debugging on a command line, and then also running in
a servlet container.

If none of the above sheds any light, please post back with the details
of the software you're using, and the locations in which you've placed
your jython.jar, your sybase jdbc jars, etc.

> Problem is that SybSQLException IS subclass of SQLException - verified
> by Eclipse IDE (type hierarchy). Similar effects were with jdbc driver
> for PostgreSQL.
>
> There's result:
> Exc org.postgresql.util.PSQLException: ERROR: syntax error at or near
> "aa"
> != subclass of java.sql.SQLException!


So it's definitely not a Sybase specific problem.

--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan
 
Reply With Quote
 
Jan Gregor
Guest
Posts: n/a
 
      08-12-2004
All tests passed ok, but problem is still there. I didn't mentioned that
mysql works fine.

My system is debian, something between woody and testing version. At
home I have similiar debian upgraded moved so far from potato to woody
to sarge - same behaviour.

Application runs from command line by 'jython TextConsole.py'. Jython is
version 2.1, running on java 1.4.2_05 (at home 1.4.1). PostgreSQL
(7.4.3) and jdbc driver (as jython) from debian testing distribution.


Jan
 
Reply With Quote
 
Alan Kennedy
Guest
Posts: n/a
 
      08-12-2004
[Jan Gregor]
> All tests passed ok, but problem is still there. I didn't mentioned that
> mysql works fine.
>
> My system is debian, something between woody and testing version. At
> home I have similiar debian upgraded moved so far from potato to woody
> to sarge - same behaviour.
>
> Application runs from command line by 'jython TextConsole.py'. Jython is
> version 2.1, running on java 1.4.2_05 (at home 1.4.1). PostgreSQL
> (7.4.3) and jdbc driver (as jython) from debian testing distribution.


I have one more thing to suggest, and that only applies if you are
"embedding", i.e. calling jython created classes from java, as opposed
to calling java classes from jython.

If you are embedding, then you are initializing the jython runtime
yourself, as opposed to having jython do that for you. In these cases,
names of java packages are not always picked up from the jython package
cache (although the class definitions are picked up if the jar is
present on the classpath).

Try adding a line like this to the top of your jython module

import sys ; sys.add_package('com.sybase.jdbc2.jdbc')

This can also be done outside jython, in the java embedding environment,
through a PySystemState object, as described here

http://sourceforge.net/mailarchive/f...&forum_id=5586

If that doesn't help, I'm afraid I'll be too busy for the next few days
to help out, though there are other people here who might be able to
contribute.

The day I've been waiting for for 7 years has finally arrived: proof
that the US retail milk supply is contaminated with a bacterium known as
Mycobacterium avium subspecies paratuberculosis. I expect to be very
busy with this, especially if the US media reacts to the story the same
way that the British and Irish media did. If you see an article on
paratuberculosis and Crohn's Disease in the media in the next few days,
you'll be happy to know that python is an essential part of the
management of two of the main related web sites: www.crohns.org and
www.paratuberculosis.org

More info on paratuberculosis in US retail food from

http://www.johnes.org/newsfiles/109216471862392.html

my-world-is-tumbling-ly y'rs

--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
FW: [Jython-users] Jython Licensing Question Pinegar, Kent T Python 0 07-24-2008 01:38 PM
FW: [Jython-users] ERROR : parsing xml in jython Divya Prakash Python 0 12-19-2006 02:49 PM
Checked exceptions vs unchecked exceptions Ahmed Moustafa Java 5 07-14-2004 01:46 PM
[Jython-users] ANN: SPIRO - a cPython->Jython bridge (amongst otheruses) David McNab Python 0 04-09-2004 10:20 AM
Custom exceptions -- inherit from exceptions.Exception? Paul Miller Python 3 11-12-2003 09:24 AM



Advertisments