473,726 Members | 2,262 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 12756
[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 FileNotFoundExc eption; # Subclasses IOException

dud_file_name = "does_not_exist .txt"

def open_file(filen ame):
return FileInputStream (filename)

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

def catch_subclass( ):
try:
f = open_file(dud_f ile_name)
f.close()
except FileNotFoundExc eption, fnfx:
print "Caught expected FileNotFoundExc eption: %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 FileNotFoundExc eption is a subclass of IOException

def catch_superclas s():
try:
f = open_file(dud_f ile_name)
f.close()
except IOException, iox:
print "Caught expected IOException: %s" % str(iox)
except FileNotFoundExc eption, fnfx:
print "Error: should not have reached FileNotFoundExc eption clause"

if __name__ == "__main__":
catch_subclass( )
catch_superclas s()
############### #########

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.SqlExc eption:
# 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.jdbc 2.jdbc.SybSQLEx ception. This is extract from my code, exception is thrown by self.db.execute Sql(iline),
def run (self):
while (1):
gr_mode= 0
iline= Readline.readli ne(":", 0)
if iline==None:
continue
iline= strip(iline)
if iline=='\q':
try:
Readline.writeH istoryFile(self .rl_history.get Name())
except:
print ("Error writing history file!")
System.exit(0)
break
if iline=='\gr':
continue Readline.addToH istory(iline) if re.match(r'^\+ ', iline):
gr_mode= 1
iline= strip(iline[2:])

try:
type, result= self.db.execute Sql(iline)
if result==None:
continue
if type=='resultSe t':
self.process(re sult)
elif type=='table':
if gr_mode:
wnd = swingWnd.Simple Swing(result.to _html())
wnd.size= (600,600)
wnd.setVisible( 1)
else:
self._print_tab le(result)
elif type=='viewSour ce' or type=='procSour ce':
self.println(re sult)
elif type=='tableDes c':
self._print_tab le(result)
elif type=='error':
self.println(re sult)
# except (SQLException, PSQLException, SybSQLException ), e:
except java.sql.SQLExc eption, 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.jdbc 2.jdbc.SybSQLEx ception.


Strange indeed. The only explanation I can think of offhand for the
exception not being caught is if com.sybase.jdbc 2.jdbc.SybSQLEx ception
is not a subclass of java.sql.SQLExc eption.

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.Excep tion
import java.sql.SQLExc eption

try:
# Insert your exception generating code here
except java.lang.Excep tion, jlx: # Catch every possible java exception
if isinstance(jlx, java.sql.SQLExc eption):
print "Exc %s is subclass of java.sql.SQLExc eption" % jlx.toString()
else:
print "Exc %s != subclass of java.sql.SQLExc eption!" % 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.jdbc 2.jdbc.SybSQLEx ception: Stored procedure 'aa' not
found. Specify owner.objectnam e or use sp_help to check whether the
object exists (sp_help may produce lots of output).
!= subclass of java.sql.SQLExc eption!
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.PSQLExcept ion: ERROR: syntax error at or near
"aa"
!= subclass of java.sql.SQLExc eption!
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.jdbc 2.jdbc.SybSQLEx ception: Stored procedure 'aa' not
found. Specify owner.objectnam e or use sp_help to check whether the
object exists (sp_help may produce lots of output).
!= subclass of java.sql.SQLExc eption!
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.SQLWar ning() # known subclass of SQLException
except java.sql.SQLExc eption:
print "Successful ly 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.

TestSubclassExc eptions.java <---------->
import java.sql;

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

Making sure that the class definition is on your classpath, instantiate
a TestSubclassExc eptions 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.jdbc 2.jdbc.SybSQLEx ception 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.hom e" 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.PSQLExcept ion: ERROR: syntax error at or near
"aa"
!= subclass of java.sql.SQLExc eption!


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.jd bc2.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 paratuberculosi s. 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
paratuberculosi s 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 paratuberculosi s 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
2108
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 generous enough to make the two languages possible, that, well, they're kinda different. I guess it was inevitable, but with Jython stuck at Python 2.1, it's not really the same language as CPython is today. You still have to type "from __future__...
0
1319
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 Applet in an AppletViewer, it runs fine. However, when run in a web browser, I am getting NullPointerException's (I copy-pasted from the Java Console these Exceptions). Please Note, I AM including jython.jar in the ARCHIVE parameter of the HTML...
4
3426
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
3682
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 passes a python object (pO) to pB. Now I require pA to be called in a java class (jC) and pass pO into jC. As pA uses non-python modules, I am not able to use Jython on this.
3
2297
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 this been done before for with jython? Another approach would be to use JPype to call the jython jar directly. My goal is to be able to script Java code using Jython - but with the twist of using Cpython as a glue layer. This would allow...
12
5920
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 says: usage: java fit.FitServer host port socketTicket -v verbose I think this is because I do not understand the jython mechanism for inheritance (yet).
3
4149
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, hence the Unix 'ls' on a Windows box C:\>cd Jython
2
2473
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 following means? I'm using JDK 1.5.0_09, under Win XP SP2. Runnnig the file " jython FILENAME" works, so I don't know what's happening. Any thoughts?
5
3608
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
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9401
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.