Servlet Compiling error - java

I developed simple servlet using Apache Tomcat 6.
Firstly I write simple Hello World print servlet. Then set CLASSPATH for servlet-api.jar and compile and copy webapps/login/WEB-INF/classes/test/HelloServlet.class. That's working fine.
After I write simple JDBC connection in the servlet. I downloaded MySQL J-Connector and set CLASSPATH like this:
C:\Program Files\apache-tomcat-6.0.32\lib\servlet-api.jar;C:\Program Files\apache-tomcat-6.0.32\lib\mysql-connector-java-5.1.16-bin.jar
then try to compile; it then shows the following message:
"Unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown"
How should I solve that?

Keep your Class.forName() under try catch block & classpath should ends with (.;) check it once.

java.lang.ClassNotFoundException is a checked exception. That means that you are required to deal with it, either by putting the call that may throw this exception inside a try { ... } catch (ClassNotFoundException e) { ... } block or by adding a throws clause to the method declaration of the method in which you make the call to the method that may throw this exception.
Read more about dealing with checked exceptions in The Catch or Specify Requirement in Oracle's Java Tutorials.

Related

Exception Handling in JS using Graal

I work on a Java application that makes fairly heavy use of Javascript to form the business logic/glue. It runs using Graal. This all works fine, but we struggle with effective error handling.
This is essentially how the JS is executed:
try {
Context context = Context.newBuilder("js").allowAllAccess(true).build()
Source s = Source.newBuilder("js", src, "script").build();
context.eval(s);
} catch (Exception e) {
LOGGER.error("Exception occurred in JavaScript:...", e);
}
So when errors happen we log them somewhere so we can do some postmortem, etc. It's possible to get the JS stack trace in these logs out of the PolyglotException that Graal throws, which is great. However, things are more complicated when some JS code has called back into Java-land, and a Java exception has been thrown:
var x = callJavaFunction("invalid parameter"); // Throws a NoSuchElementException, for example
The PolyglotException has an asHostException() method that returns the original Java-land exception, and my code that executes the JS files is smart enough to understand this and produce a useful error log. The problem arises when the JS code has tried to catch this itself, for whatever reason:
try {
var x = callJavaFunction("invalid parameter"); // NoSuchElementException
} catch (e) {
doSomeCleanup();
throw e;
}
Now we have lost the original Exception, and even worse, the JS-stack trace now just shows us the catch block, instead of where the cause was. isHostException() returns false, because this is just a JS error now. I cannot find a way to get at the original cause, which makes diagnosing errors quite difficult, especially when they have come out of a production system. The original Java exception message ends up in the JS-error object, which is helpful, but we don't have the stack trace, which is not.
What approaches can I take to try and address this?
One thought I had: Can I hook into the GraalVM and get a callback whenever a host-exception is thrown? At least that way I could have a log saying "the following Java Exceptions were thrown during execution" which I could attach to the error report. So far I've not been able to find a way to achieve this.

Class.forName() is not working with a particular class

I am trying to load with java reflection a bunch of classes. Everything seems working fine (I am handling the exception if the class is not found).
However there is a particular class that is raising another exception that is not thrown by call to the Class.forname() but by an internal method and so I cannot even catch it.
Here is my code:
try {
URL url = Class.forName(qualifiednameOfTheClass);
} catch (ClassNotFoundException ex) {
// ok class not found can be handled
} catch (Exception e){
// catch every other exception just to try to get the strange exception
}
So with this code everything is working, I am using it on lots of classes and it's working (sometimes it finds it sometimes it doesn't).
However there is one case that is not working properly and I cannot understand why. If qualifiednameOfTheClass = sun.security.krb5.SCDynamicStoreConfig my code is raising an exception:
Exception in thread "mythread-1" java.lang.UnsatisfiedLinkError: no
osx in java.library.path at
java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886) at
java.lang.Runtime.loadLibrary0(Runtime.java:849) at
java.lang.System.loadLibrary(System.java:1088) at
sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:67)
at
sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:47)
at java.security.AccessController.doPrivileged(Native Method) at
sun.security.krb5.SCDynamicStoreConfig.(SCDynamicStoreConfig.java:39)
at java.lang.Class.forName0(Native Method) at
java.lang.Class.forName(Class.java:190) at
com.myclass.getJARFromClassForName(JavaId.java:510)
at com.myclass.getJARUrl(Id.java:550) at
com.myclass.collectInformation(Graph.java:366)
at
com.myclass.createNode(Graph.java:166)
at com.myclass.Graph.(Graph.java:143) at
com.myclass2.run(myclass2.java:246)
at java.lang.Thread.run(Thread.java:745)
So as you can see in the error we have this strange exception that cannot be caught even with a generic catch like in my code and I cannot understand why it has been raised and what actually is this osx library (I am on linux)
EDIT: The only thing that I found is this link http://www.straub.as/java/pocketapi/index7.html but is in german and so I read it with google translate and I don't know if I got it right but is saying that the classes listed there cannot be reproduced with Class.forname() itself.
Is it true? Is there a reason why this cannot be loaded with reflection or am I doing something wrong?
"Cannot be caught" because it's an Error, not an Exception. I'd recommend reviewing the object hierarchy in the JDK for Throwable.
Try changing that to Throwable and you'll have better luck catching. I don't know why the error is happening.
This looks like a JNI class that's using native code. I don't know what you're doing, but this looks like a bad idea to me.
This is not how this class expects to be loaded and loading this internal class directly doesn't appear to work. You need to load the class using the standard encryption API so that this class can be loaded as expected, or possibly not loaded at all (it could be code which will only work on OSX)
As you can see in the link you have provided, there are some classes where this method fails.
When calling this method on these objects, Java needs first to load additional stuff, as this is platform specific stuff which is not shipped by default. In your case, it is Kerberos, a security API.
As you can see in its Documentation, it searches for some files in specific paths (java.library.path). As it can not find it there, it throws an error.
Note that the error UnsatisfiedLinkError does not refer to finding the class name for sun.security.krb5.SCDynamicStoreConfig itself. It refers to not finding the native library in the paths provided by java.library.path.
This path itself points, for example on Windows, to C:Windows/system32/.
However, you may catch this error with catch(Error e), note that an Error is not an Exception (Throwable hierarchy).
Be aware that catching an Error in general is no good idead as you can not be sure if the JVM can recover from it.

Console not showing Runtime Exception

I found a really weird bug within my Java Code
Even when i force a RuntimeException in my program it is not recognized by the JVM.
Here a demo of what I have written
private static void someMethod(){
//Some Code
if(true)
throw new RuntimeException();
// More Code
}
I added the if(true) to prevent the unreachable code message, just for testing.
But I think that the real problem is that there is some unhandled Exception in my code, which I cant really log, because the printStackTrace() is missing, or else i should get a console log.
Also I get the plain text: Exception while removing reference.
But its no System.err message, it just look like System.out
Are there any other methods of logging exception, excpect the default console, and what could cause a exception to be unhandled?
NOTE: I use following external libraries: JNativeHook, JLayer, Apache Commons IO
Full GitHub repo
The Exception should occur in CsgoSounds.java at line 944
OS: Windows 10, jre version: 1.8.0_60
There are checked Exceptions and unchecked ones (everything that extends runtime exception).
The compiler force you to deal with checked exceptions (with a try catch or a throws declaration). You are not forced to deal with Unchecked exceptions. But you can, just add a try catch around your code, then you can call printstacktrace on it.
JNativeHook was blocking all console outputs. I had to enable the function first.
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);
did the job.

Catch SQL RaiseError in jsp

I am developing a database and some JSP Pages to perform CRUD operations on it.
I cannot catch exceptions related to my SQL Code in my JSP Code.
For Example:
I have this part of code where I raise an error in T-SQL:
IF #existing > 0
BEGIN
RAISERROR ('ID primário ja existe', 1, 1)
RETURN 0
END
IF (#CategoriaId IS NULL)
BEGIN
RAISERROR('O CategoriaId não pode ser nulo',1,1)
RETURN 0
END
I need to call the function where I raise those errors in JSP code.
Heres a part of the JSP Code:
try
{
rs = stmt.executeQuery(sql);
}
catch (Exception u)
{
out.println(u.toString());
}
And it never returns the error from T-SQL.
However I know that the function reaches the catch statement because if I throw a println("test") in there it writes test on the jsp page.
I always get this exception : >com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
This is an insert operation I'm doing, and if I write the correct values it inserts without any problems. But even when it inserts it throws that exception.
Edit: I tried u.getMessage() already
You really should read the exception message you get.
The reason you don't get the exception from the database is probably because it's masked by the exception you get from the java.
I'm a .net guy myself, the last time I've worked with java was about 17 years ago, so I'm not familiar with the correct method you should use, but it's probably not executeQuery.
According to this post, you should use execute instead.
Update
After our conversation in the comments I've done some digging and found this pearl in MSDN.
Note this part:
A RAISERROR severity of 11 to 19 executed in the TRY block of a TRY…CATCH construct causes control to transfer to the associated CATCH block. Specify a severity of 10 or lower to return messages using RAISERROR without invoking a CATCH block.
This means that your raiserror's severity parameter should be somewhere within the range of 11 to 19.
I was struggling with this with a Spring Boot project of mine. The Exception thrown would not contain the RAISERROR that exists in a MSSQL table's trigger. The ExceptionUtils.getRootCauseMessage(e) would only get the message "The transaction ended in the trigger".
Up until now I had the MSSQL Driver loaded through my projects maven pom.xml file.
The moment I placed the MSSQL Driver in my JVMs jre/lib/ext folder the RAISERROR messages where included in the Java Exception.

Source not found for Null Pointer Exception

I've come across some really strange behaviour in my Java code. There is a exception shown on my Eclipse log console saying Exception:java.lang.NullPointerException with no reference to the code where it occurred.
On debugging I found out a line where this occurred and so put it in try-catch hoping I catch it. However it didn't return in catch block.
The strange part being even though there's exception thrown at the line immediately after it executes and the execution continues normally.
Can some one please tell me the probable cause?
I could have attached the source code but I have checked the parameters and all seem fine.
My main reason for this post is to learn about such behavior if any of you coders ever came across.
Probably a problem with Eclipse. I have seen that behaviour before, and restarting Eclipse solved the problem.
Please check whether your builder is activated and the changed source code is build automatically. Otherwise your code changes will never get it into your runtime application.
I am pretty sure, that the executed source code is different to the source code shown in your editor.
If you see the exception's message but no stack trace, that is caused by code that looks like this:
try
{
// something which causes the exception
}
catch (final Exception err)
{
System.out.println(err);
}
The problem with this code is that it only prints the result of the exception's .toString() method. For most exceptions this is just the exception class and the message. This code omits the stack trace, thus making it much harder to debug the problem.
If the exception is to be caught, then change the code to look like this for the stack trace to be included in the output:
try
{
// something which causes the exception
}
catch (final Exception err)
{
err.printStackTrace();
}

Categories