473,386 Members | 1,820 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

jython and java exceptions

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
Jul 18 '05 #1
7 12723
[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
Jul 18 '05 #2
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
Jul 18 '05 #3
[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
Jul 18 '05 #4
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

Jul 18 '05 #5
[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
Jul 18 '05 #6
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
Jul 18 '05 #7
[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
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Dave Benjamin | last post by:
Hey good people, I've been doing a lot of simultaneous Jython and CPython programming lately, and just wanted to say, with no intended ill will toward any of the individuals who have been...
0
by: Ike | last post by:
I have a signed JApplet which has a JTextArea wherein one can put Jython Script. Upon clicking a JButton, the script is executed. The script which executes to code is listed below. If I run the...
4
by: angel | last post by:
A java runtime environment includes jvm and java class (for example classes.zip in sun jre). Of course jython need jvm,but does it need java class. Thanx
5
by: Maurice Ling | last post by:
Hi, I have read that this had been asked before but there's no satisfactory replies then. I have a module (pA) written in python, which originally is called by another python module (pB), and...
3
by: Jim Hargrave | last post by:
I've read that it is possible to compile jython to native code using GCJ. PyLucene uses this approach, they then use SWIG to create a Python wrapper around the natively compiled (java) Lucene. Has...
12
by: Mark Fink | last post by:
I wrote a Jython class that inherits from a Java class and (thats the plan) overrides one method. Everything should stay the same. If I run this nothing happens whereas if I run the Java class it...
3
by: donkeyboy | last post by:
All, I'm having issues installing Jython on Windows XP. I've looked on the web and this newsgroup but to no avail. Any suggestions? The shell listing is below: NB I've got Cygwin installed,...
2
by: donkeyboy | last post by:
All, I've tried the jythonc compiler to try and create an applet to see how it works, but I get a number of Java compile errors that are way above my knowledge. Does anyone know what any of the...
5
by: sarup26 | last post by:
Hello .. I would like to know more about Python and Jython? What is the difference between both of them? What is the future for Jython and which are the areas where it is used? Swot
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.