How to new an InvocationException in Java? - java

How could I new an InvocationException in Java ?
InvocationException needs an ObjectReference in its constructor, I don't know how to create one.

Do you mean InvocationTargetException?
From the API: Is a checked exception that wraps an exception thrown by an invoked method or constructor.
Not sure what you try to achieve, maybe share some code and describe your intentions, however if you want to extend this exception then:
package .....;
import java.lang.reflect.InvocationTargetException;
public class SampleException extends InvocationTargetException {
protected SampleException() {
super();
}
public SampleException(Throwable target) {
super(target);
}
public SampleException(Throwable target, String s) {
super(target, s);
}
#Override
public Throwable getTargetException() {
return super.getTargetException();
}
#Override
public Throwable getCause() {
return super.getCause();
}
}
Maybe you want to override getTargetException with something specific to your requirement to catch InvocationTargetException and rethrow with your specific exception?
try{
.....
}catch(InvocationTargetException e){
//Do something with e?
throw new SampleException(); //Rethrow?
}
As I said not much information given.

Related

Java 8 - throw multiple generic checked exceptions in lambda

In a project I am working at, I have found a class which wraps all methods of its super-class in some elaborate exception handling. It looks similar to that:
public void method1() throws ExceptionA {
String exceptionString = "";
try {
super.method1();
} catch (ExceptionA e) {
exceptionString = // <convert the exception to string in an elaborate way>
throw e;
} finally {
// <an elaborate logger call which uses value of exceptionString>
}
}
public void method2() throws ExceptionB, ExceptionC {
String exceptionString = "";
try {
super.method2();
} catch (ExceptionB | ExceptionC e) {
exceptionString = // <convert the exception to string in elaborate way>
throw e;
} finally {
// <an elaborate logger call which uses value of exceptionString>
}
}
// ... <a bunch of other methods like this>
I immediately though "Wow, how could would it be to have one generic wrapper and just call it in every of these methods. The class would be like 10x shorter!".
So I got to work.
This is where I got stuck:
private interface ThrowingMethod<E extends Exception> {
void run() throws E;
}
public <E extends Exception> void wrapMethod(ThrowingMethod<E> method) throws E {
String exceptionString = "";
try {
method.run();
} catch (Exception e) {
exceptionString = // <convert the exception to string in an elaborate way>
throw e;
} finally {
// <an elaborate logger call which uses value of exceptionString>
}
}
public void method1() throws ExceptionA {
wrapMethod(super::method1); // works
}
public void method2() throws ExceptionB, ExceptionC {
wrapMethod(super::method2); // Error in Eclipse: "Unhandled exception type Exception"
}
// ... <a bunch of other methods like this>
In conclusion, this approach works for methods that throws only one type of checked exception. When method throws multiple checked exceptions, Java assumes that the exception type is Exception.
I tried to add more generic parameters to ThrowingMethod and wrapMethod but it doesn't change anything.
How can I get a functional interface to work with multiple generic exceptions?
When you expand your interface to use two type variables, i.e.
private static interface ThrowingMethod<E1 extends Exception,E2 extends Exception> {
void run() throws E1, E2;
}
public <E1 extends Exception,E2 extends Exception>
void wrapMethod(ThrowingMethod<E1,E2> method) throws E1,E2 {
// same as before
}
the rules regarding the type inference do not change and they are the same for both type variables. E.g. you can still use
public void method1() throws ExceptionA {
wrapMethod(super::method1);
}
as before, as the compiler simply infers the same single exception type for both type variables.
For the method declaring two exceptions, it won’t pick up one for the first type variable and the other for the second; there is no rule which could tell the compiler which exception to use for which type variable.
But you can help the compiler out in this case, e.g.
public void method2() throws ExceptionB, ExceptionC {
wrapMethod((ThrowingMethod<ExceptionB, ExceptionC>)super::method2);
}
which is the best you can get with this approach.
So your goal is just to wrap a bunch of methods with logging? A typical way to handle this is with AOP. You'd just create a single pointcut that matches all those methods, and you wouldn't have a bunch of repeated boilerplate. No need for those interfaces or wrapping methods.

Java -- thrown exceptions in implemented/overridden methods [duplicate]

The code below gives a checked error to throws Exception:
import java.io.IOException;
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
#Override
public void ss99 () throws Exception {}
// ...
}
while the one below compiles fine:
import java.io.IOException;
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
#Override
public void ss99 () throws NullPointerException {}
// ...
}
On what logic is Java doing this-- any ideas?
TIA.
The throws keyword indicates that a method or constructor can throw an exception, although it doesn't have to.
Let's start with your second snippet
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
#Override
public void ss99 () throws NullPointerException {}
}
Consider
some ref = getSome();
try {
ref.ss99();
} catch (IOException e) {
// handle
}
All you have to work with is with your interface some. We (the compiler) don't know the actual implementation of the object it is referencing. As such, we have to make sure to handle any IOException that may be thrown.
In the case of
SQL2 ref = new SQL2();
ref.ss99();
you're working with the actual implementation. This implementation guarantees that it will never throw an IOException (by not declaring it). You therefore don't have to deal with it. You also don't have to deal with NullPointerException because it is an unchecked exception.
Regarding your first snippet, slightly changed
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
#Override
public void ss99 () throws Exception { throw new SQLException(); }
}
Consider
some ref = new SQL2();
try {
ref.ss99();
} catch (IOException e) {
// handle
}
So although you are handling the exception declared in the interface, you would be letting a checked exception, SQLException, escape unhandled. The compiler cannot allow this.
An overriden method must be declared to throw the same exception (as the parent) or one of its subclasses.

exception handling in the implemented method

The code below gives a checked error to throws Exception:
import java.io.IOException;
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
#Override
public void ss99 () throws Exception {}
// ...
}
while the one below compiles fine:
import java.io.IOException;
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
#Override
public void ss99 () throws NullPointerException {}
// ...
}
On what logic is Java doing this-- any ideas?
TIA.
The throws keyword indicates that a method or constructor can throw an exception, although it doesn't have to.
Let's start with your second snippet
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
#Override
public void ss99 () throws NullPointerException {}
}
Consider
some ref = getSome();
try {
ref.ss99();
} catch (IOException e) {
// handle
}
All you have to work with is with your interface some. We (the compiler) don't know the actual implementation of the object it is referencing. As such, we have to make sure to handle any IOException that may be thrown.
In the case of
SQL2 ref = new SQL2();
ref.ss99();
you're working with the actual implementation. This implementation guarantees that it will never throw an IOException (by not declaring it). You therefore don't have to deal with it. You also don't have to deal with NullPointerException because it is an unchecked exception.
Regarding your first snippet, slightly changed
interface some {
void ss99() throws IOException;
}
public class SQL2 implements some {
#Override
public void ss99 () throws Exception { throw new SQLException(); }
}
Consider
some ref = new SQL2();
try {
ref.ss99();
} catch (IOException e) {
// handle
}
So although you are handling the exception declared in the interface, you would be letting a checked exception, SQLException, escape unhandled. The compiler cannot allow this.
An overriden method must be declared to throw the same exception (as the parent) or one of its subclasses.

Having generic AsyncTask handle any Exception

I have created an generic AsyncTask class, so that I can catch all Exceptions thrown when task method is executed:
public abstract class Poc<ParamType, ReturnType>
extends AsyncTask<ParamType, String, ReturnType> {
abstract ReturnType task(ParamType... param);
#Override
protected ReturnType doInBackground(ParamType... param) {
try {
return task(param);
} catch (Exception e) {
// Make some Toast display the exception.
}
return null;
}
}
I try to implement the above class by doing some thing like:
public class Use {
public static void runIt() {
new Poc<String, Boolean>() {
#Override
Boolean task(String... param) {
return SomeObject.someMethodThatCanThrowAnException(param);
}
}.execute("Some String");
}
}
However, it keeps complaining about wanting me to add try/catch statements. Even when I know that task will only be called from doInBackground which wraps it.
Can I somehow suppress this? Or what is the proper approach without having to add try/catch to every single class that subclasses Poc?
As the compiler is trying to tell you, you need to declare your function as being able to throw things using throws Exception.
In this case, you would want the abstract method to be able to throw.

Throwing exceptions and catching them elsewhere

I was wondering if it was possible to write a method to throw an exception and have another method catch these exceptions.
For example,
public static void checkCircle() {
try {
checkPixel(a);
checkPixel(b);
checkPixel(c);
} catch (MyException e) {
System.out.println("not circle");
}
private static void checkPixel(anything) {
if (img.getRGB(xValue, yValue) != pOrigColour) {
throw new MyException();
}
}
class MyException extends Exception {
public MyException() {
}
public MyException(String msg) {
super(msg);
}
}
Thing is I want to the checkPixel method to throw a MyException, indicating that there is no circle, regardless of the results of the other calls.
Yes, it is possible. In your method declaration, you can add a throws clause, which indicates that your method might throw an exception.
In your case, you should modify your method declaration like this:
private static void checkPixel(anything) throws MyException {
// ...
}
You should note that exceptions should be used for... exceptional situations. Using them for simple error handling is highly unconventional, and adds unnecessary burden on users of your classes. In your case, you might want to add a boolean hasCircleAtLocation () method that would return true if there is a circle at the provided location.

Categories

Resources