Try/Catch not catching exception - java

I'm trying to do java class loading. I'm using eclipse (luna) with 1.8.0_25 on a macos yosemite.
I'm using the following code in order to do it. It's working, until it reaches a class that has a dependency that isn't contained inside the jar that I'm loading classes from. Neither on the environment.
I'm not interested in this classes, so, it's safe to ignore then. So, I put it inside a try/catch and just log it.
But, when the exception occurs, the execution is canceled.
The exception (summarized) is:
Exception in thread "main" java.lang.NoClassDefFoundError: org/aspectj/runtime/internal/AroundClosure
Caused by: java.lang.ClassNotFoundException: org.aspectj.runtime.internal.AroundClosure
It rises at the exact line that is inside the inner try/catch block.
Why? Shouldn't the try/catch just log it and move on?
URLClassLoader ucl = null;
try {
URL url = Utils.getURIFromPath(jarFilePath).toURL();
URL[] urls = new URL[] { url };
ucl = new URLClassLoader(urls);
for (String tmp : classes) {
String clazz = tmp.substring(0, tmp.indexOf(".class")).replaceAll("/", ".");
try {
ucl.loadClass(clazz);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
} catch (MalformedURLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
if (ucl != null) {
try {
ucl.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}

NoClassDefFoundError is an Error, not an Exception, you should never1 try to catch an error, as stated here, catching it won't help you.
Check your classpath and fix it.
1 In some cases you might want to catch an error and handle it accordingly, as stated in the comments, maybe "never" is a little bit strong

Ok then try this:
catch (Throwable e) {
LOGGER.error(e.getMessage(), e);
}
Although using the above code will handle both Errors and Exceptions for you (both extend from Throwable), but it's not the right way to do it, only in very special cases do we handle errors using try-catch, errors are something we need to check in our code and resolve them.

It seems that one of the classes that you're using, probably one of the classes that you're trying to load with loadClass, has a dependency to classes from AspectJ, but the ClassLoader does not find the AspectJ classes. A possible solution is to make sure that AspectJ is on your classpath when you execute this.
It might also be that AspectJ already is on the classpath. If that's the case, it's just that your URLClassLoader doesn't know of your ClassPath. You might want to construct the URLClassLoader with a parent ClassLoader in place, like this:
ucl = new URLClassLoader(urls, getClass().getClassLoader());
The reason why the program doesn't just move on is that you're catching Exception. The hierarchy is class Throwable, class Exception extends Throwable and class Error extends Throwable, so catch (Exception e) will not catch Error. You might want to use catch(Exception | NoClassDefFoundError e) in this special case. Usually, catching Errors is not a good idea, but sometimes there are reasonable exceptions for errors like NoClassDefFoundError, OutOfMemoryError or StackOverflowError.

Related

Catching undeclared CheckedException

I'm using a third-party java library and this library class has a method called doSomething:
Library.doSomething();
In the course of the doSomething method, it sometimes throws a java.net.SocketException, but the doSomething method does not declare the SocketException as a checked exception. So when I try to write:
try {
Library.doSomething();
} catch (java.net.SocketException error) {
error.printStackTrace(); // and do other recovery stuff
}
I get the following compiler error:
Unreachable catch block for SocketException. This exception is never thrown from the try statement body
However, I know that at runtime the doSomething method frequently throws the SocketException. I know that I can catch a generic java Exception and then check to see if it is a SocketException, but is there any more elegant way to catch the SocketExceptions thrown by this third party closed source library?
Thanks!
Edit - It turned out the SocketException is wrapped in a WebServiceException and I just missed the wrapped exception in a crowded error log. So there really isn't any question to answer. Sorry for the confusion.
Mena's answer is very good, but I just want to state that there are ways (4 of them if I recall correctly, I mention them in the comments) to throw check exceptions that are not declared.
As a solution I suggest catching something general like Exception and check the type of the caught exception (using instanceof is recommended).
You should write
catch (Exception e) {...}
Because compiler returns error if the catch block will never (or hardly ever) execute. In the catch block, you can compare the Exception using "instanceof" statement to get an information about specific exception.
I know that I can catch a generic java Exception and then check to see if it is a SocketException, but is there any more elegant way to catch the SocketExceptions thrown by this third party closed source library?
There is no alternative that will actually deal with the exception; i.e. allow you to actually handle it in the normal fashion.
Basically, the 3rd-party library has broken Java's checked exception rules. It is faulty and should be fixed.
FWIW, the code to work around the 3rd-party library bug is a "delicate":
try {
callNastyMethod();
} catch (Exception ex) {
if (ex instanceof SocketException) {
// handle the exception we are expecting
} else if (ex instanceof RuntimeException) {
// unexpected runtime exceptions should be rethrown
throw (RuntimeException) ex;
} else {
// deal with any other checked exceptions; for example.
throw AssertionError("Unexpected checked exception", ex);
}
}

This is about the Exception Handling and the Exception Matching Concept in Java

I am new to Java. I was going through the Exception Handling Concept but I stuck at one point here.
We know that whenever the Exception is thrown Java will try to find by looking at the available catch clauses in the top down manner. If it doesn't find one, it will search for a handler for a supertype of the Exception.If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack.
Also if most specific exceptions is placed above the more general exceptions handler then it results in the COmpilation error.
Suppose we have a code as shown below:-
try{
// do not know what kind of exception it will be throwing but I am sure that it is IOException
}
try{
// Here the FileNotFoundException is thrown
}
catch(IOException e){
//Do exception handling stuff
}
catch(FileNotFoundException f){
//Do exception handling stuff`
}
Now this code will result in the compilation error because the Supertype of the exception is present above the actual exception.
SO why the first paragraph do not support this concept. i.e After checking JVM will found the appropriate exception(FileNotFoundException) and should not bother about IOException clause, but run into compilation error instead.
Please throw some light on it.
Also let me know If I am able to explain what I want to??
It looks like you are misunderstanding the try concept. You only have one try followed by the catch clauses.
try{
// do not know what kind of exception it will be throwing but I am sure that it is IOException
// Here the FileNotFoundException is thrown
}
catch(IOException e){
//Do exception handling stuff
}
catch(FileNotFoundException f){
//Do exception handling stuff`
}
This code will throw an error at compile time because for FileNotFound Catch Block the code will be unreachable as it's already handled by IO Exception and FileNotFound is subclass for IOException
Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException
FileNotFoundException is a subclass of IOException gives us the choice of either treating all IOExceptions the same, or catch some of IOExceptions subclasses individually
Code snippet has fundamental mistakes
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it
Recommended reading:
https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

How do I extract a stacktrace from threads in Eclipse?

I'm very confused with handling errors on runnables passed to a threadpool.
I am doing everything by the book (literally, I'm adhering to Goetz' "Concurrency in Practice") and I'm not capturing any errors that Eclipse is showing me, and I'm getting weird NoClassDefFoundErrors even though my buildpath looks fine.
I tried killing my local repo and recloning it to get a fresh project build, but still getting the error. And none of my try-catches or System.out.println's are working either. Is there any way Eclipse can give me a better view of the error? Or a way to actually get the error handler's to work?
//ThreadPool and runnable that is failing, even with error captures
MyPriorityThreadPool.execute(new RunWithPriority(priority) {
Throwable thrown = null;
#Override
public void run() {
try {
batch.buildData();
} catch (Exception e) {
thrown = e;
}
finally {
if (thrown != null) {
thrown.printStackTrace();
}
}
}
});
}
I'm not quite sure what you're trying to accomplish, but the reason you're not catching the NoClassDefFoundError in your code is that you're catching Exception instead of Throwable or Error. Exception is more specific than Error and not what NoClassDefFoundError inherits from, so NoClassDefFoundError isn't caught by your catch expression.

Catch unchecked exceptions in java

I'm writing application and I need to catch all existing exceptions including checked and uncheked exceptions. Is it possible to catch unchecked exceptions before application is terminated and write them in file for example?
Both Error and Exception extend Throwable:
public static void main(String args[]) {
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
From the point made by #u6f6o - You should only do this in main because some of the Throwables (e.g. OutOfMemoryError) mean that your JVM is probably in a very shaky state.
You could use
Thread.setDefaultUncaughtExceptionHandler
see: http://www.tutorialspoint.com/java/lang/thread_setdefaultuncaughtexceptionhandler.htm
or http://www.javamex.com/tutorials/exceptions/exceptions_uncaught_handler.shtml
Use Exception class to catch your exceptions (this class is parent) and put it into a data structure in way of storing them and then, write them in a File.http://docs.oracle.com/javase/7/docs/api/index.html?java/lang/Exception.htmlhttp://docs.oracle.com/javase/7/docs/api/index.html?java/io/OutputStreamWriter.html
Catching unchecked exceptions in Java can be more tricky than it appears as they are Runtime exceptions. But, remember you don't have to catch runtime/unchecked exceptions; only checked exceptions. It is a bad practice, but virtually all of them extend Throwable and using catch Throwable might be a way to do this. However, you may want to have a look at the following documentation http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
If you would like to write them into a file in Android, then within the catch block, you would have to obtain the exception message and write that message (a String) into the file, using one of the FileWriter APIs for Android. But remember, the catch bock should catch all Exceptions of type Throwable, even though this can be really ugly, as this will cover most unchecked exceptions in Java.
You can catch unchecked exception in catch block.
like
try {
int i = 9 / 0;
} catch (ArithmeticException d) {
d.printStackTrace();
}

Which line in a long Java 'try' block is throwing an exception?

Is there a way to find out which line in a try block is throwing an exception?
I'm working on Java in Eclipse which looks like
try {
//Lots of code. Seriously. Lots.
} catch (Exception e){
throw new OtherException();
}
I'm hitting an exception in the try block, (which is then caught). How do I figure out where it's being thrown from?
Problems
The stack trace only shows the line in the catch block for the OtherException
Removing the try/catch block isn't straightforward, as there are many exceptions declared as thrown which are required to be caught in order for the code to compile.
It feels like there should be a straightforward way of doing this.
Note: I didn't write this code ;-)
Use the cause parameter for Exceptions (see here):
try {
//Lots of code. Seriously. Lots.
} catch (Exception e){
throw new OtherException(e); // Trick is here
}
This way you get the cause exception as well in the stacktrace.
You can use throw new OtherException(e);. As the documentation explains, this constructor constructs a new exception with the specified cause.
In Eclipse, you can set a breakpoint triggered by an exception. See Add Java Exception Breakpoint.
For this particular case, you'll need to ensure that "Suspend on caught exceptions" is ticked.
Once Eclipse breaks into the debugger, you'll have a lot of tools at your disposal. You'll see the call stack, will be able to examine variables etc.
Just print stacktrace or run on debug mode
e.printStackTrace()
Pass the exception e in your OtherException constructor when throwing it. It will give you the complete stack trace with the exact line throwing the exception:
catch (Exception e) {
throw new OtherException(e);
}
If OtherException doesn't have a constructor that takes an Exception or Throwable you could do:
catch (Exception e) {
OtherException o = new OtherException();
o.initCause(e);
throw o;
}
You can also try printing out the error message to the console: System.out.println(e.getMessage());
Breakpoints are very useful though, since you can then trace through the code and see exactly when it gets to the catch block.

Categories

Resources