Java: How do I catch an exception created inside the Method.invoke? - java

It seems like I can't catch exceptions in my code when the method was called from the Method.invoke method. How can catch it from inside the method itself?
void function() {
try {
// code that throws exception
}
catch( Exception e ) {
// it never gets here!! It goes straight to the try catch near the invoke
}
}
try {
return method.invoke(callTarget, args);
}
catch( InvocationTargetException e ) {
// exception thrown in code that throws exception get here!
}
Thanks!

You can get the real cause of the MethodInvocationException by checking its getCause() method that will return the exception thrown from function()
Note: you might need to call getCause() recursively on the returned exceptions to arrive at yours.
Note: getCause() returns a Throwable, which you will have to check for its actual type (e.g. instanceof or getClass())
Note: getCause() returns null if no more "cause" is available -- you have arrived at the base cause of the execption thrown
Update:
The reason why the catch() in function() is not getting executed is that xxxError is not an Exception, so your catch won't catch it -- declare either catch(Throwable) or catch(Error) in function() if you don't want to declare all specific errors -- note that this is usually a bad idea (what are you going to dio with an OutOfMemoryError?.

One reason that you can't catch UnsatisfiedLinkError with Exception is that UnsatisfiedLinkError is not a subclasses of Exception. In fact, it is a subclass of Error.
You should be careful about catching Error exceptions. They almost always indicate that something really bad has happened, and in most cases it is not possible to recover from them safely. For instance, an UnsatisfiedLinkError means that the JVM can't find a native library ... and that whatever depended on that library is (probably) unusable. Generally speaking. Error exceptions should be treated as fatal errors.

MethodInvocationException means you're calling the method wrong, it shouldn't have even gotten to inside your try block. From the docs:
Signals that the method with the specified signature could not be invoked with the provided arguments.
Edit: That's if this is the Spring MethodInvokationException, the Apache Velocity one does wrap function exceptions.

You throw exceptions as normal. The fact its inside an invoke makes no difference.
public class B {
public static void function() {
try {
throw new Exception();
} catch (Exception e) {
System.err.println("Caught normally");
e.printStackTrace();
}
}
public static void main(String... args) throws NoSuchMethodException, IllegalAccessException {
Method method = B.class.getMethod("function");
Object callTarget = null;
try {
method.invoke(callTarget, args);
} catch (InvocationTargetException e) {
// should never get called.
throw new AssertionError(e);
}
}
}
prints
Caught normally
java.lang.Exception
at B.function(B.java:15)
... deleted ...
at B.main(B.java:26)
... deleted ...

Related

Throw Exception catch childException... why not?

Say I have a method doSomething() which throws a checked exception, then in my main method I enclose doSomething() in a try catch.
Question:
Say I throws Exception in doSomething(). Why can't I catch (ChildException e) in my main method?
I know I can't and that I must catch Exception, but I don't understand why.
ChildException extends Exception.
If I throws ChildException and catch Exceptionthen there's no problem understandably so. Why not the other way round?
You can catch ChildException in your main method, but because the method you call is defined as throws Exception, you will also have to catch Exception, because the compiler does not know that doSomething is only throwing ChildException. If that is what you want, then you should define doSomething as throws ChildException instead.
For example with your current setup you could do:
try {
doSomething();
} catch (ChildException e) {
// handle child exception
} catch (Exception e) {
// handle other exceptions
}
As commented by MC Emperor, order of catch blocks is important, if you'd reverse the order and catch Exception first, then that block will also handle ChildException, and the ChildException-specific block will not be used.
Alternatively, change doSomething():
public void doSomething throws ChildException {
// ...
}
If your code throws ChildException child, you can catch it with Exception parent , because ChildException extends Exception, so child is assignable to parent i.e. you can write something like
Exception parent = child;
But if your code says you are throwing an Exception, the compiler takes you at face value and assumes that the exception type thrown by your method can be of any subclass of Exception or of the class Exception itself.
For example , your method may throw another ChildException2. So, in that case it is not assignable to ChildException in the catch clause of main method. The ChildException2 is neither handled nor declared.
So, the compiler doesn't allow you to continue with just catching the ChildException and asks you to either catch the type Exception or declare it.

What is the meaning of this statement from a blog saying a function has to declare Throwable at method signature to catch it?

I am trying to understand exception handling in Java and i keep running into variations of the below mentioned confusing statement in several articles -
There are several reasons why catching instance of java.lang.Throwable is bad idea, because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.
This is from http://javarevisited.blogspot.com/2014/02/why-catching-throwable-or-error-is-bad.html#ixzz4hQPkFktf
However, this code compiles -
class CatchThrowable
{
void function()
{
try
{
throw new Throwable();
}
catch (Throwable t)
{
}
}
public static void main(String[] args)
{
try
{
}
catch (Throwable t)
{
}
}
}
Both main and function are able to catch Throwable without declaring that they throw it. My understanding is that the throws keyword is used to declare the checked exceptions which a function throws, not those which it catches. Please clarify the quoted statement.
The statement:
order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.
is basically wrong.
You just have to understand the following. There is a exception Hierarchy
A method can throw all types of exception, it just depends on your needs which one you catch and which one not.
It is also not a good idea to catch Error (which includes that you should also not catch Throwable) because there are some severe JMV-VirtualMachineError's like OutOfMemoryError which you usually not should catch.
But this has nothing to do which the fact, what a method declares in its throws part.

Java Exception handle case

public void backendExecute(Map appParams, BackendTaskMetaData metaData) throws Throwable {
try {
PeriodicTaskData ptd = (PeriodicTaskData) appParams.get(PeriodicTaskData.PARAM_KEY);
String bizKey = ptd.getBusinessKey();
} catch (Exception e) {
LogServices.app.error("RPTPeriodicReportGenTask:"+ e.getMessage());
}
}
With regards to the method above, if object pointed to is null, would come across as NullPointerException, I want to know if this exception would be caught or thrown to the invoker method? thanks
Exception is a parent class of NullPointerException, so it will catch it and not throw it to the calling method.
As you are catching Exception class and NullPointerException is its subclass , exception will get catched not throwed.
Regard to above method, if object ptd is null, would come across nullpointexception,
Yes.
i want to know this exception would be catch or throw it to invoker method?
The exception would be caught by the handler. The handler will catch Exception and any exception that is descended from it. NullPointerException is a subclass of RuntimeException which is (in turn) a subclass of Exception. Therefore, it will be caught.
Now, if this may be just an illustrative example ... but it is a bad idea to:
declare a method as throws Throwable, or
catch Exception ... unless you are about to terminate the application.
Declaring a method as throwing Throwable makes it next to impossible for the caller to know what exceptions could be thrown. Instead, the compiler will insist that the caller catches ... or propagates Throwable.
Catching Exception has the problem that you will catch every subtype of Exception ... including various unchecked exceptions that 1) you are not expecting, and 2) are probably symptoms of bugs that you cannot safely recover from.
NullPointerException is a subclass of Exception and thus will be catched, however it is recommended that you don't try and catch runtime exceptions. It is better to avoid them.
For example a null pointer could be avoided by doing the following:
if(ptd != null) {
ptd.getBusinessKey();
} else {
//Notify the user in some way or do something else.
}
catch (Exception e)
means that this will catch any exception (i.e. any subclass of Exception) thrown inside the preceding try block - which, yes, includes NullPointerException. Note that this is generally considered a bad practice, as you almost always will want to handle different sorts of exceptions in different ways, hence the need for multiple catch statements.
For instance, consider a method that could potentially throw an IllegalAccessException at compile time or a NullPointerException at runtime - it's difficult to imagine a situation where you'd want to handle them the same way, so you'll typically want to do something like this:
try {
PeriodicTaskData ptd = (PeriodicTaskData) appParams.get(PeriodicTaskData.PARAM_KEY);
String bizKey = ptd.getBusinessKey();
} catch (NullPointerException e) {
//do something
} catch (IllegalAccessException e) { //for example...
//do something different
}

Is it possible to ignore an exception?

In Java, is it possible to make a method that has a throws statement to be not checked.
For example:
public class TestClass {
public static void throwAnException() throws Exception {
throw new Exception();
}
public static void makeNullPointer() {
Object o = null;
o.equals(0);//NullPointerException
}
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm forced to handle the exception, but I don't want to
}
}
You can try and do nothing about it:
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) { /* do nothing */ }
}
Bear in mind, in real life this is extemely ill-advised. That can hide an error and keep you searching for dogs a whole week while the problem was really a cat(ch). (Come on, put at least a System.err.println() there - Logging is the best practice here, as suggested by #BaileyS.)
Unchecked exceptions in Java extend the RuntimeException class. Throwing them will not demand a catch from their clients:
// notice there's no "throws RuntimeException" at the signature of this method
public static void someMethodThatThrowsRuntimeException() /* no need for throws here */ {
throw new RuntimeException();
}
Classes that extend RuntimeException won't require a throws declaration as well.
And a word from Oracle about it:
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
There are 3 things you can do :
Throw a RuntimeException (or something extending a RuntimeException, like NullPointerException, IllegalArgumentException,...), you don't have to catch these as they are unchecked exceptions.
Catch the exception and do nothing (not recommended) :
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) {
// Do nothing
}
}
Change exceptionTest () declaration to say that it throws an Exception, and let the method calling it catch the Exception and do what is appropriate :
public static void exceptionTest() throws Exception {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm no more forced to handle the exception
}
In Java there is two kinds of Exceptions, Checked Exceptions and Unchecked Exceptions.
Exception is a checked exception, must caught or thrown.
NullPointerException is a RuntimeException, (the compiler doesn’t forces them to be declared in the throws claus) you can ignore it, ,but it still may occur in the Runtime, and your application will crash.
From Exception documentation:
The class Exception and any subclasses that are not also subclasses of
RuntimeException are checked exceptions. Checked exceptions need to be
declared in a method or constructor's throws clause if they can be
thrown by the execution of the method or constructor and propagate
outside the method or constructor boundary.
From the RuntimeException documentation:
RuntimeException is the superclass of those exceptions that can be
thrown during the normal operation of the Java Virtual Machine.
RuntimeException and its subclasses are unchecked exceptions.
Unchecked exceptions do not need to be declared in a method or
constructor's throws clause if they can be thrown by the execution of
the method or constructor and propagate outside the method or
constructor boundary.
No, it raises a compiler error. Being a checked exception, you must either catch it or propagate it by declaring your method as potentially throwing it.
Check this and this.
Throw a RuntimeException or an exception which is derived from RuntimeException. Then the compiler will not force you to catch it.
The other answers are right, in that they correctly tell you what you should do, but it is actually possible to throw a undeclared checked exception. There are a few ways this can be done; the simplest is:
public void methodThatSecretlyThrowsAnException() {
Thread.currentThread().stop(new Exception());
}
or if your goal is to wrap an existing method that does declare its exception
public void methodThatSecretlyThrowsAnException() {
try {
methodThatAdmitsItThrowsAnException();
} catch(final Exception e) {
Thread.currentThread().stop(e);
}
}
(Needless to say, you should never do this.)
Just catch an exception and dont do any thing with it, leave it as it is and catch the generic exception in case you are not aware of the specific exception
try{
//Your logic goes here
}
catch(Exception e)//Exception is generic
{
//do nothing
}
AS I know, it's impossible in the case. Only unchecked exception, compiler can skip to check. such as RuntimeException.
You can use a loophole in the Java Compiler. Add the following code:
public RuntimeException hideThrow(Throwable e) {
if (e == null)
throw new NullPointerException("e");
this.<RuntimeException>hideThrow0(e);
return null;
}
#SuppressWarnings("unchecked")
private <GenericThrowable extends Throwable> void hideThrow0(Throwable e) throws GenericThrowable {
throw (GenericThrowable) e;
}
You can catch the exception, then invoke hideThrow with the exception to throw it without the compiler noticing. This works because of type erasure. At compile time, GenericThrowable represents RuntimeException because that is what we are passing. At run time, GenericThrowable represents Throwable because that is the basic type in the type parameter specification.
It is not advisable to avoid an exception with an empty catch block even though you are completely sure that is not going to fail under any circumstance. Sometimes, we are not aware of the human factor.
If you are sure that an exception is very unlikely to happen (if not impossible) you should create your own Exception and and wrap the unexpected exception in it.
For example:
private class UnlikelyException extends RuntimeException {
public UnlikelyException (Exception e){
super (e);
}
}
Then wrap your code with a try-catch block and throw your exception, which you don't have to catch
try {
// Your code
} catch (Exception e) {
throw new UnlikelyException(e);
}

java: can't rethrow exception: Unhandled exception type Exception

I'd like to catch an exception, log it, set a flag, and the rethrow the same exception
I have this code:
public Boolean doJobWithResult() {
boolean result = true;
final Feed feed = Feed.findById(feedId);
try {
feed.fetchContents();
} catch (Exception ex) {
result = false;
Logger.info("fetching feed(%d) failed", feedId);
throw ex;
}
return result;
}
But eclipse complains at throw ex, telling that "Unhandled exception type Exception", and suggests me to add a try-catch block around it.
In fact, I want the process calling this method to handle the exception, and not handle it myself... I just want to return true if everything goes ok, and log it if there's an exception
On the other hand, I can wrap the exception inside another exception, but I can't throw the same one..
any idea?
I think there are various things to mention here:
You either want doJobWithResult() to return true on success and false on failure, or return nothing on success and throw an exception on failure.
Both at the same time is not possible. In the first case, catch the Exception, log it and return false, in the second case change your signature to return void and throw an exception and handle it in the caller.
It's a Don't to catch an exception, log it and rethrow it. Why? Because a potential caller of your method does not know that you are already logging it, and migh log it as well.
Either throw an exception (in which case the caller has to deal with it) or catch it and handle it (log it).
Note that throwing Exception does not give the caller of your method any clue about what might potentially go wrong in your method, it's always better to throw more specific exceptions, or to wrap an exception in a user-defined one and rethrow it.
Moreover, if you throw Exception, a caller might be tempted to catch Exception without noticing that this will also catch every RuntimeException (since its derived from Exception), which might not be desired behavior.
Your doJobWithResult method needs to declare that it can throw Exception:
public Boolean doJobWithResult() {
becomes
public Boolean doJobWithResult() throws Exception {
You can throw the same exception if you add throws Exception to your method signature.
Otherwise you can throw a RuntimeException.
public Boolean doJobWithResult() {
boolean result = true;
final Feed feed = Feed.findById(feedId);
try {
feed.fetchContents();
} catch (Exception ex) {
result = false;
Logger.info("fetching feed(%d) failed", feedId);
throw new RuntimeException(ex);
}
return result;
}
In such a case, you won't need to indicate that public Boolean doJobWithResult() throws something but make sure you handle it properly later on (catch or expect your thread to stop... it's a RuntimeException afterall).
Since Exception is checked, an alternative to catching the Exception is to declare your method as throwing it:
public Boolean doJobWithResult() throws Exception {
// ...
}
If doJobWithResult doesn't have to handle the exception, then remove the catch block and add "throws Exception" to the method signature. The exception logging can be done in the class/method that have to deal with the Exception in a corresponding try/catch block.
There is no need to set the result as false in the catch block, as the value won't be returned(as we are throwing an exception).
Your method should also declare that it throws an exception and so the client will be forced to handle it.
Also consider using a more specific exception which will be thrown in this particular case.
Add throws Exception to your method. You also don't need to add result = false; in your catch block.
I think the way you handle this exception is really appropriate if any failure of feed.fetchContents() method cannot be recovered. (Idea is better to halt rather than continuing)
Apart from that I would suggest you to use more specific exception hierarchy.
And another thing I got from effective java book is if you write such a method you must document with #throw (in comments) with the reason.
You could throw an unchecked exception
Logger.info("fetching feed(%d) failed", feedId);
throw new RuntimeException(ex);
I spent the last hour looking for it since not even the Complete Reference book mentions this explicitly: unhandled throw ThrowableInstance works only with unchecked exceptions.. And only runtime exceptions are unchecked. By unhandled I mean something like this:
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // re-throw the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
This example is taken verbatim from the Complete Reference book (9th edition).
The first throw statement i.e throw new NullPointerException("demo"); is handled by the following catch block, but the second throw statement i.e. throw e; is unhandled by the demoproc() method. Now this works here and the above code compiles successfully because NullPointerException is a runtime/ unchecked exception. If the e instance were a checked exception or even an Exception class instance then you'd get an error saying the exception e is unhandled and you'd either have to handle it within demoproc() or you'd have to explicitly declare that demoproc() throws an exception using throws in the method signature.

Categories