I've got my own class that implements com.ibm.websphere.asynchbeans.Work with the following run method:
#Override
public void run() {
try {
agentManager.loadLibContent(agent);
} catch (Exception e) {
ErrorAnalizer.report(e);
log.error("some err: "+e.getMessage());
//this.setStatus("error");
//throw new RuntimeException(e);
} finally {
workLoadManager.delRunTask(getTaskHistory());
}
}
This work-class is passed to startWork(Work var1) method of com.ibm.websphere.asynchbeans.WorkManager.
When I get an exception in the try block it is being caught and logged, no problem.
But I want that exception to go upper till it reaches the very first method that called websphere's startWork.
How to do that? Runnable does not let to throw checked exception. RuntimeException didn't help. It seems startWork swallows it somewhere inside.
Bad thing that this first method is located in another project module and I can not reach it from catch block to pass info to do some job.
I also tried to setStatus in my work-class and then get it after but looks like startWork don't let me to change passed object.
Any help is appreciated. Thank you!
You need to use the WorkItem.getResult method:
MyWork myWork = ...
WorkItem wi = wm.startWork(myWork);
...
try {
myWork = (MyWork)wi.getResult();
...
} catch (WorkException e) {
Throwable cause = e.getCause();
...
}
Then, there are two options:
The catch block in your run method can store the exception in an instance field, and then you can retrieve it after calling getResult.
The run method throws an unchecked exception, and it should be available as the cause of the WorkException that is caught.
To get the result of submitted asynchbeans Work, you can store a reference to the com.ibm.websphere.asynchbeans.WorkItem and invoke getResult() which will return the result of your work if it completed successfully, or it will throw a com.ibm.websphere.asynchbeans.WorkException which wraps the exception thrown by the Work implementation.
Here is an example:
// Submit the work
WorkItem workItem = workManager.startWork(new MyWork());
// Wait for the work to be done for up to 60s
ArrayList<WorkItem> items = new ArrayList<WorkItem>();
boolean workFinished = workManager.join(items, WorkManager.JOIN_AND, 60*1000);
if(workFinished)
try {
MyWork work = workItem.getResult();
// if we get here, the work completed without errors
} catch(WorkException e) {
throw e.getCause(); // this will be the exception thrown by your Work impl
}
else {
// the Work did not finish in 60s
}
Related
I am using core java to develop a testing framework. In my application I have a parent method which calls ten different child methods, where each method can throw its own exceptions. The requirement is to provide detailed log information about the execution of parent method which contains information like total time taken to execute the method, time taken to execute each child method, log any exceptions etc. I am using multiple try catch finally blocks for this.
My question is, What's the best way to skip the execution of remaining child methods if one of the child method throws an exception? For eg: If method 4 throws an exception, I want to log that exception and go to the end and log the time taken by parent method until then.
I tried using boolean variable initializing it to true at the beginning of parent method. I am checking if the boolean varible is true before executing each child method. Whenever an exception is thrown, I am marking the boolean variable false.
My psuedocode looks like this:
public String parentMethod(){
boolean execute = true;
if(execute) {
try event1;
catch(Event1Exception e1)
log e1; execute = false;
finally log event 1 time taken;
}
if(execute) {
try event2;
catch(Event1Exception e2)
log e2; execute = false;
finally log event 2 time taken;
}
and so on ....
log total time taken;
In my actual code I have about ten different events which throw their own exceptions, sometimes more than one. With this approach, assigning execute = false for each exception caught and then again checking the value of execute seems clunky. Is there a better approach than this, without using any additional plugins?
You could just log the exception and rethrow it:
public String parentMethod(){
try {
try {
...
} catch(Event1Exception e1) {
log e1;
throw e1;
} finally {
log event 1 time taken;
}
try {
...
} catch(Event2Exception e2) {
log e2;
throw e2;
} finally {
log event 2 time taken;
}
} catch (Event1Exception | Event2Exception | ... e) {
// Can be safely ignored
}
}
Or if you don't want to handle each exception separately you can just do:
public String parentMethod(){
try {
try {
...
} finally {
log event 1 time taken;
}
try {
...
} finally {
log event 2 time taken;
}
} catch (Event1Exception | Event2Exception | ... e) {
log e
}
}
Hi Sree what I will recommend to use method calling in a single try block. Write all the catch blocks with different exceptions at the end of this try block. Whenever any method throws the exceptions, control will directly go to the corresponding catch block, skipping remaining method calls.
For e.g.:
try
{
method1(); // Exception1 occured
method2(); // skipped
method3(); // skipped
}
catch(Exception1 e)
{
// control goes here
// End timer
// Calculate difference
// Store difference in global variable
}
catch(Exception2 e)
{
}
catch(Exception3 e)
{
}
method1()
{
// start timer
// your code
// End timer, if no exception occurred
// Store difference in global variable
}
Hope this will help. :-)
If you are only interested in the first exception, then you could execute all the events in a single try-catch block, and handle any thrown exception in the catch block.
try {
event1();
event2();
// etc
} catch(Exception e) {
//Handle
}
Otherwise start a thread for each process and handle failures by terminating all the other threads as soon as one fails.
A non-answer here: don't do that.
It sounds like you are simply violating the single responsibility principle here. A class/method should have one purpose, and one purpose only!
Meaning: it is already suspicious that you have to call 10 different other methods - in a context that so complicated that you think it is worth putting up a question here.
So, my recommendation would rather to step back and see if you can re-factor your code base to end up with less different method calls bundled together somehow!
And when you really can't avoid calling 10 methods, simply use multicatch:
try {
foo();
bar();
...
} catch (ExceptionA | ExceptionB | ...
And beyond that: you should definitely work on preventing code duplication. Something like this comes to mind:
private interface CallContext<T, X extends Throwable> {
T execute() throws X;
}
private static <T, X extends Throwable> T runTimed(CallContext<T, X> context) throws X {
prepare timer
T result = context.execute();
put timed value somewhere
return result;
}
Used something like this:
try {
SomeT t = runTimed(() -> return foo());
} catch (ExceptionA a) ...
Looks like you are overthinking a bit. try-catch construction already gives you what you want. consider this:
try {
method1();
method2();
method3();
method4();
} catch(Exception e) {
//do error hanlig here (log it for example)
}
In this case say mathods 1 and 2 executed successfully and method3 threw an exception - The control will go to catch block and method4 will NOT be executed. which if I undestood you correctly is exactly what you need
I understand the basic try-catch, where we put methods that could possibly throw exceptions in the try block. But when we need to check if something is wrong, and throw an exception, is it correct to use the code below? And the exception is caught, the program will continue to execute?
I can't tell why the try is needed here, but without it eclipse says 'syntax error'. Thanks for your help in advance!
public run (){
if (something !=true) {
try{
throw new Exception();
}catch (Exception e){
}
Yes that is correct. You have to use try since that is where the exception-throwing code is entered and where exceptions are caught (just using a catch block won't serve any purpose)
Generally speaking, exceptions are used to let the calling code handle errors in your method.
If you just want to handle the error in run, you don't need exceptions:
public void run() {
if (something != true) {
// handle it
}
}
If you want the calling code to handle the error instead, this is where you need exceptions:
public void run() throws Exception {
if (something != true) {
throw new Exception();
}
}
And where you call run, use a try/catch block:
try {
run();
} catch (Exception e) {
// handle it
}
It is also recommended that you don't throw an Exception instance, use a custom subclass instead.
How would one write an "if statement" that checks if an error occurred in a method if so it would start a separate method that deals with the error otherwise open the next method
It is called Exception Handling.
Example:
void someMethod()
{
try
{
// Open a File
}
catch(FileNotFoundException e)
{
// Call another method
}
finally
{
// this block executes whether exception occurs or not
}
// Continue execution
}
Use a try catch statement for this. Assumign you want to crash out if the first method errors (after dealing with the exception) then the below format should work
try {
methoda();
} catch(Exception e) {
methodToDealWithError(e);
throw(e);
}
methodb();
i think try-catch block will do it for you. call your first method in try block, then call your method which deals with exceptions in catch block.
Why not just use Exceptions? Make the method throw an exception on error, catch the exception in the calling code, place error handling in the catch block??? That's what Exceptions are for!
It depends on how the method reports the error. If it returns "false" upon error you can do a trivial test:
boolean res = method();
if (!rest) {
// manage error
}
If the method however raises exception, you have to catch them with:
try {
method();
} catch (Exception e) {
// Manage exception or raise
}
Actually it depends on how method is implemented. Can you give some more info ?
methodA: The first method, it throws an exception in case en error occurs
methodB: next Method to execute, if no error occurs
methodC: error dealing method
try{
methodA();
methodB();
catch(Exception e){
methodC();
}
use Exception handling by using try catch block as
try {
Place Your Code Here...
} catch(Exception e) {
callAnotherMethodHere();
}
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 ...
I need to do some initialization and clean it up in case of any exception. I'd still like the exception to be passed to the caller. The problem is I now have to declare this method as throws Throwable and then I have to explicitly handle this throwable in the caller, just as if all procedures don't throw Throwables implicitly already. Stupid isn't it?
try {
init_step1();
init_step2();
}
catch (Throwable th) {
clean();
throw th;
}
One way of doing this is to perform the cleanup in a finally block instead, noticing whether there's been an exception by whether you actually got to the end of the try block or not:
boolean success = false;
try {
// Stuff here
success = true;
} finally {
if (!success) {
clean();
}
}
Stupid is fighting against checked exceptions. You have to throw something different if you don't want to require every caller to handle it. just throw a RuntimeException
public void myMethod() throws RuntimeException {
try {
init_step1();
init_step2();
}
catch (Throwable th) {
clean();
throw new RuntimeException(th);
}
}
why do you catch Throwable in first place anyway? init_step1() and init_step2() doesn't throw an exception?
#Jon Skeet's solution is the cleanest. Another solution which may interest you.
try {
// Stuff here
} catch(Throwable t) {
clean(t);
// bypasses the compiler check
Thread.currentThread().stop(t);
}
I would only suggest using this approach if you needed to know the exception thrown. e.g. For resources I have which are closable, I record the exception which triggered their close. This way if I try to use the resource and it is closed I can see why it is closed.
private void checkClosed() {
if (closed)
throw new IllegalStateException("Closed", reasonClosed);
}