I have an exception I'm trying to catch whenever my VNC connection is killed (whenever I restart my VM) and I'm trying to ignore it to continue my Jython script. I'm not sure how to write a try catch statement to catch the exception since it's originating from Java. This is for a sikuliX script.
Exception in thread "Thread-7" com.tigervnc.rdr.EndOfStream: EndOfStream
at com.tigervnc.rdr.FdInStream.readWithTimeoutOrCallback(FdInStream.java:192)
at com.tigervnc.rdr.FdInStream.overrun(FdInStream.java:142)
at com.tigervnc.rdr.InStream.check(InStream.java:37)
at com.tigervnc.rdr.InStream.check(InStream.java:44)
at com.tigervnc.rdr.InStream.check(InStream.java:45)
at com.tigervnc.rdr.InStream.readS8(InStream.java:55)
at com.tigervnc.rdr.InStream.readU8(InStream.java:64)
at com.tigervnc.rfb.CMsgReaderV3.readMsg(CMsgReaderV3.java:50)
at com.tigervnc.rfb.CConnection.processMsg(CConnection.java:67)
at org.sikuli.vnc.VNCClient.processMessages(VNCClient.java:246)
at org.sikuli.vnc.VNCScreen$1.run(VNCScreen.java:82)
at java.lang.Thread.run(Unknown Source)
#abarnert You really saved my day. I have encountered the same problem as OP posted. The jython code is as following:
################################################################
# CONFIG DEFINITIONS
################################################################
#GOOD_IMAGE_URL = "http://192.168.1.15/11111111.png"
BAD_IMAGE_URL = "http://192.168.1.15/111111112222.png"
def exceptionDemo(urlPath):
try:
print "exceptionDemo is starting"
myImg = imageio.ImageIO.read(URL(urlPath))
if myImg is None:
print "Img is None"
else:
print "Img is OK"
return myImg
#except Exception, err:
except java.lang.Exception as err:
print "Exception is here"
print err
finally:
print "Finally is here"
the purpose of this code is to download the image file specified by urlPath. when the ulrPath is bad(in this case, the 111111112222.png does not exist.), I would like to catch the exception in order to handle this issue properly.
If I simply use the normal "except Exception, err" to catch the exception, the program will just abort without any information. The print statements in except and finally section are supposed to execute, however, that didn't happen. What I get is nothing after seeing "exceptionDemo is starting".
I spent days on dealing with this problem, searching on google again and again, leaving no stone unturned. After days of investigation, I get the idea that there are two sorts of exceptions when you programming in jython, one is python exception, the other is java exception. The reason for this problem is that either jython or SikuliX in this case, has suppressed the java throwables. I am not very familiar with jython, so it's just my guess and it has not been verified(I am more familiar with native Python and Java).
At first, I doubt it's ImageIO - the native java package's problem. I wrote a simple java demo to test ImageIO by giving the bad image url, it worked great, a nice "javax.imageio.IIOException: Can't get input stream from URL" had been thrown out. Then, I know that my guess is right. The java exception somehow did not well handled in jython or SikuliX. The point here is that even if this is the root cause, I still need a simple and elegent way to deal with this problem. I tried some other workarounds, but nothing is as good as I've expected. The essential part of this problem is not about downloading the image, it's about catching the exception.
It was not until I simply replace "except Exception, err“ with "except java.lang.Exception as err" that the code is working like a charm. I got all the printouts that I expected.
Your posts really saved my day. Good job and many thanks.
The following references are very helpful in my investigation:
javax.ImageIO methods fail silently
trap exceptions comprehensively in Jython
https://www.jython.org/jythonbook/en/1.0/ExceptionHandlingDebug.html
Finally, If there were any tips I would like to offer to people who find this post, it should be "STAY AWAY FROM THIS KIND OF HALF-BAKED SHODDY HYBRID LANGUAGE", You will get neither the expediency of Python, nor the robustness of Java, the only thing that you eventually will get is a big waste of your time.
=================================================================
Update on 2019-08-02:
As a follow-up of this post, I offer you a "buy one get more free" deal. It contains a heck of surprise brought you by Jython and Sikuli X.
1, DO NOT USE ANYTHING DEPENDS ON Netty in Jython. This includes httplib and urllib2, etc. It will fail if you try to GET/POST something in a loop, use Requests or java.net instead.
for details, please refer to this post: Why does this Jython loop fail after a single run?
2, DO NOT USE type() function in Sikuli X. This function is normally used in python to determine the type of an object, however, Sikuli X use it to mimic the keyboard input function. If you insist, you should import builtin first, then call it like this:
# -*- encoding: utf-8 -*-
import __builtin__
if __name__ == '__main__':
a=10
print __builtin__.type(a)
for details, please refer to these:
How to check variable type using “type” function in Sikuli
https://answers.launchpad.net/sikuli/+question/239574
These are some pitfalls that I have experienced in jython and Sikuli X, if you have to work with these two things, good luck and wish you have fun.
As explained in Exception Handling and Debugging, you handle Java exceptions in Jython the same way you handle Python exceptions:
As stated previously, it is a common practice in Jython to handle Java exceptions. Oftentimes we have a Java class that throws exceptions, and these can be handled or displayed in Jython just the same way as handling Python exceptions.
A Java exception is, as far as your code is concerned, just an instance of some Exception subclass.
Of course that subclass happens to live in, e.g., java.lang instead of builtins or another stdlib module, and it will (almost?) always have java.lang.Exception as an intermediate ancestor before getting all the way back to Exception, but generally, you don't care about that.
So, wherever you're calling the Java code that's throwing this exception… just put a try: / except Exception as e: or except java.lang.Exception as e: or more specific type, the same way you would when calling Python code.
Related
Expectedly, this SystemClock.sleep(paramMaybeNegative) is being used in a multi-threaded context, if that is relevant. The negative would come from an uninitialized object property in some yet unforseen circumstance.
Here is the documentation regarding what I am asking about:
developer.android.com:SystemClock.sleep(long). It doesn't mention an exception or forever or something else that might be expected.
Putting this question here to remember to answer it later and handle the consequences in some code I am writing, as much as in hopes someone knows what to expect already and wants to type about it before I get to (super-informative and helpfully interesting factoids about SystemClocks also welcome:).
It calls Thread.sleep(millis) which throws an IllegalArgumentException.
You can find out by reading the src code, or by trying out.
From reading and guessing at source code running in emulator I would expect it to not throw error and act like a SystemClock.sleep(0); it throws to logcat and crashes app:
java.lang.IllegalArgumentException: timeout arguments out of range
at java.lang.VMThread.sleep(Native Method)
...
...
...
I am as likely as not looking at wrong source file.
I have my program working and all done (java). It's a short and easy program for a job interview. I handle stuff like improper input format by throwing a custom exception. Is that the best way to do it or should I just make a print statement?
Exceptions are only useful if they will be handled by other code.
If you're writing a reusable library, you should by all means throw an exception.
There is nothing more frustrating than calling a third-party library that logs errors to the console instead of telling your code about them.
However, if you're writing a standalone utility, it's nicer to print friendly error messages than an ugly stack trace.
The most flexible approach is to write reusable code that throws exceptions, then add catch blocks in main() (or elsewhere in the standalone portion) that prints friendly messages.
If you handle improper format inline is the code readable? If so - fine, if not - throw an exception and handle it elsewhere
Are you able to handle improper format properly in the place you are parsing it or maybe some more generic method/class/module is actually calling your routine and should decide what to do? If the latter is the case -> throw an exception
In general - it depends. If you can handle this special situation "inline" - you can do it (make sure it's readable). If not - throw an exception.
Here's a good reference on exception best practices. You should make sure you are following these.
In your particular case (based on the details you have provided) a user may upload/select a file that has bad data. You program should handle that by catching any basic Java runtime issues and returning information to the user (not "Exception in thread..." but something more readable to a user). If you are checking for these alpha characters then you should just handle that (with an error to the user) without throwing an exception - unless this is truly the behavior you want.
Exception are cause when the program cannot work in a normally correct manner.
The exceptions get more complicated and increase in numbers when you evolve from j2se to j2ee.
For a stand alone application
If your application is just a extremely simple calculator then you may just completely forget about exception because your user input would be filtered and one of the few exception would be division by zero
If your application is a simple utility tool say screen capture , then if your file cannot be saved (exception at file i/o) then all you need to do is simply terminate all your task and say some error message to the user.
For an advanced project of example 2 , you need to save the image in a temp , and perform saving of file once the issue is rectified
For a enterprise scaled and distributed application
Here transaction(inter related activities) is involved . Here a simple message to the user is also needed at times and also handle(do needed changes to related transactions) the exception !
If the application is distributed in many countries then exception in one traction needs alteration in another server in another country , this demands optional incorporation of a some thing that uses JMS API(message sending inside application)
JPA (java persistence api) implicitly rolls back the database on event of a exception and provides facility to do so for interrelated transactions . But still the roll back only affects the database and not the instance variable(object values)
and at all times you don't want to user to read your exact stack trace that says error at line number .....
I know that I can either catch the NameNotFoundException from a call to PackageManager.getPackageInfo or loop through the PackageInfo list returned by PackageManager.getInstalledPackages to know whether a particular package is installed, but both of these seem either long winded or ugly. On my personal phone, I have more than 300 packages installed, so I'd hate to have to do that operation every time I need to check. And catching an exception as a means of performing application logic just makes me feel wrong all over. Am I missing the isPackageInstalled method somewhere, or do I just need to implement it myself using one of the above mentioned techniques? And if the latter, which would be considered the faster and less resource intensive option?
Since PackageManager.getInstalledPackages() returns a List, you don't need to loop through it manually. You can use List.contains() or List.containsAll() to accomplish the task in one line of code. Of course, this doesn't change the efficiency since both methods likely contain a loop themselves.
If using the API really bugs you then you might look into a hack involving the following
Bash shell expression that gets the PM list
Java Runtime expression
Java Pipes and buffers and streams
Java NIO
Java grep
So the bash expression would be :
pm list packages -f | sed 's/^package.//' | awk -F"=" ' { print $2" "$1 } ' | sort
and of list of references for handling stdout from the 'pm list' in a way that might wind up being faster...
PipedBuffers
NIO/grep
Runtime/streams
Handling a NameNotFoundExcepetion should not make you feel "wrong all over" IMHO. According to the documentation this exception will be thrown if the package does not exist since api level 1. Using try/catch statement is very similar to using an if/then statement to test for a null value.
In this case it should not be considered a workaround or a hack as you are using the documented and expected return value of an exception to determine if a package exists.
I would assume this method to be faster than iterating through the List returned by getInstalledPackages(). However, I don't know what steps android takes prior to returning a NameNotFoundExcepetion. This would make an interesting benchmark test.
I'm not aware of any other practical method to test for an installed package.
I wrote some benchmarks and tested catching the exception vs a few different ways of fetching the installed packages and looping through them. Here is my result
Calling PackageManager.getPackageInfo and catching the NameNotFoundException took between 1 and 4 ms in all cases whether the requested package was installed or not, and I made sure to also include cases where this was the first call to the PackageManager for a particular run of the app and as a subsequent call just in case the framework does any caching of this information per app launch.
Calling PackageManger.getPackageInfo took between 1 and 1.5 seconds in all cases as well.
Calling getPackageInfo and catching the exception to determine if the package isn't installed is by far the faster way to check.
I am writing part of a PHP web application (which will be used in a high school bug finding contest) where the user must find bugs in a given Java program. As a part of this, when the Java program executes, we want to highlight the lines of the source of the Java program where the code has executed. To do this, all we need are the line numbers of the source that have been executed, that is, the code path (or is it called code coverage?). We will highlight the lines in the source file using the line numbers.
We will be using PHP's shell-exec() to execute the Java program and the tool to get the code path (whatever that will be). What is the easiest way of getting the line numbers of code path?
Thank you very much!
Here is a picture that describes what we would like
PHP interperts the code, which means it runs over the source each time you run the program. This has the benefit of blowing up as the code is read (which makes line number printouts trivial); however, it often is expensive in other ways, as you cannot optimize deeply (or do any pre-runtime error checking).
Java compiles its code into a JVM assembly language called "bytecode." This means that what is running doesn't generally have access to (or even use) the source code. That said, there are techniques. A compiled Java class has the ability to add "extra data" and one of those "extra data elements" is a line number table, which is an index allowing someone running the assembly to "look up" the line number as the compiler recorded it.
This generally works ok, with the considerations that: compilers often don't mark up every instruction, the source code may not be available, optimization might make certain inner chunks of code not function in ways that facilitate pointing to the input code text.
How code coverage tools "fix" this is that they generally insert into the code (at the assembly level) a large number of commands that effectively act as logging statements to a format that allows the tool to determine which path through the code was actually followed. This is then mapped back through the line number table as best as possible and then used to highlight lines within the original source file.
If you want something with finer resolution (something that can process which portion of a line was executed) then you need to dig deeper. Eventually you might even consider writing your own compiler (or compiler extension) which will store your own custom line number table that overcomes the shortcomings of the current solutions.
Tricks like throwing exceptions (as Shiven has mentioned) and parsing out the line number do work; however, they pollute your code with odd exception processing for items that really aren't exceptional, just to "get the line number". Due to the code clutter and the generally poorer runtime performance of exceptions, I tend to avoid such solutions (but they do work).
Anyway, hopefully this will give you a view as to why it doesn't always work exactly the same way as PHP.
You could get a linenumber if you compile the program with the -g option, do a printStackTrace(), capture the trace output and extract the linenumber from there.
Take a look at Cobertura. It computes coverage and stuff like that, and if it doesn't already do it, it should be relatively easy to add the line number collecting to it.
There's a very hackish attempt to do that, but that's so slow that you may not be able to use it in production https://bitbucket.org/jowu/myriapod/wiki/Home
I have never done or seen anything like this but it does seem like an interesting problem. My thought would be to use the java debugger (jdb) to run the code, rather than just the java command.
You can step through the code line by line (via the step command in jdb) and each time a line executes its line number is spit out. This would require a little help from the PHP side (it would have to parse the line number as well as execute the next step command) but the line numbers are there. Here is a sample output from a very basic java program.
Java (TestClass.java)
public class TestClass {
public static void main(String[] args) {
System.out.println("foo");
System.out.println("bar");
}
}
jdb (jdb TestClass after running javac TestClass.java)
Initializing jdb ...
> stop at TestClass:3
Deferring breakpoint TestClass:3.
It will be set after the class is loaded.
> run
run TestClass
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
>
VM Started: Set deferred breakpoint TestClass:3
Breakpoint hit: "thread=main", TestClass.main(), line=3 bci=0
3 System.out.println("foo");
main[1] step
> foo
Step completed: "thread=main", TestClass.main(), line=4 bci=8
4 System.out.println("bar");
main[1] step
> bar
Step completed: "thread=main", TestClass.main(), line=5 bci=16
5 }
main[1] step
>
The application exited
Try referring to this link JVMDI
You can try accessing the values of the program counter and then map it onto the lineNumberTable .
OR
I think JVMDI has a method which can access the line number of the executing code.I'm not sure of the latter,refer the to the link above and hope it helps.
Im using Java (JNA) to use a function in a third party .dll file. The functions I'm calling are returing the integer value 1.
After reading, I've discovered that this return value is traditionally 0 if everything runs correctly.
Was wondering if this is always the case or if theres any way to determine what it should be?
In the .h file bundled with the .dll it has the comment
// rc: EXIT_SUCCESS means NO ERROR
After the function.
Check actual dll documentation, there should be the way to tell what's wrong.
If nothing helps try calling GetLastError() WinAPI - some meaningful error code might be reported.
Also try to look at debug output during function call - some traces might be there even in Release build
Yes, zero typically means success in the C/C++ world.
In the days before exception handling you had to have a way to indicate failure and the return value was pretty much reserved for failure/success. As for what '1' means, you will have to look in the header of the dll for the function that is returning '1' and see if they included anything about error conditions. There are too many possibilities without seeing the code or knowing more about the dll to provide any easy answers.
What is the name of the function? What is it attempting to do? What can you do if you know the function failed?