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.
Related
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
}
Good afternoon,
I'm currently working with the code from:
https://github.com/kevinsawicki/http-request
I'm attempting to refactor the code as applicable to clear all the Android Studio warnings before I include it in a project I'm working on. Currently I'm working with the following nested abstract class:
///////////////////////////////////////////////////////////////////////////////////////////////
protected static abstract class Operation<V> implements Callable<V> {
protected abstract V run() throws HttpRequestException, IOException;
protected abstract void done() throws IOException;
public V call() throws HttpRequestException {
Log.d(TAG, "in HttpRequest nested class Operation call");
boolean thrown = false;
try {
return run();
} catch (HttpRequestException e) {
thrown = true;
throw e;
} catch (IOException e) {
thrown = true;
throw new HttpRequestException(e);
} finally {
try {
done();
} catch (IOException e) {
if (!thrown) {
throw new HttpRequestException(e);
}
}
}
}
} // end Operation
This is producing the following warning for having a throw inside a finally block:
I've been looking at this for a while but I can't seem to find a way to factor out this warning. I did see this other answer:
throws Exception in finally blocks
However I would really prefer to not introduce another function. If I was to introduce a closeQuietly function, would that go inside or outside the nested class listed above? Please advise, thanks!
It's just a warning. If you read the explanation it says (emphasis mine)
While occasionally intended, such throw statements may mask exceptions thrown and tremendously complicate debugging.
If you need to do it, then do it, but just make sure it's actually what you want to do and understand the implications (it's akin to saying "do you really want to do this?!"). Not all of IntelliJ's warnings can be eliminated.
Edit based on follow up: You have to ask yourself if your framework needs to throw that exception in the finally block. You can implement a similar approach to what was linked without using another function (just replace the throw statement in finally with a log statement), but that might not be desirable. It depends entirely on the potential error conditions.
If, for example, you're expecting done() to run into issues whenever you've previously received an IOException or an HttpRequestException then you probably don't need to throw anything in the finally block (just log it). But, if you need to make sure you alert the user if something went wrong trying to clean up, then you do need to throw there and you should ignore the warning.
I suppose you could do something like this:
protected static abstract class Operation<V> implements Callable<V> {
protected abstract V run() throws HttpRequestException, IOException;
protected abstract void done() throws IOException;
public V call() throws HttpRequestException {
Log.d(TAG, "in HttpRequest nested class Operation call");
boolean thrown = false;
try {
return run();
} catch (IOException e) {
throw new HttpRequestException(e);
} finally {
try {
done();
} catch (IOException e) {
// handle the IOException
}
}
}
} // end Operation
If an HttpRequestException is ever thrown it'll be thrown by the method, you still transform the IOException into an HttpRequestException (not quite sure why you want to do that), and in the finally block you would need to catch and handle the IOException appropriately.
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();
}
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);
}
Is it possible to catch a method in the current class the try-catch block is running on? for example:
public static void arrayOutOfBoundsException(){
System.out.println("Array out of bounds");
}
.....
public static void doingSomething(){
try
{
if(something[i] >= something_else);
}
catch (arrayOutOfBoundsException e)
{
System.out.println("Method Halted!, continuing doing the next thing");
}
}
If this is possible how will it be the correct way to call the catch method?
If this is not possible, could anyone point me in the right direction, of how to stop an exception from halting my program execution in Java without having to create any new classes in the package, or fixing the code that produces ArrayOutOfBoundsException error.
Thanks in Advance,
A Java Rookie
What you are wanting to do is handle an Exception.
public static void doingSomething(){
try {
if (something[i] >= something_else) { ... }
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Method Halted!, continuing doing the next thing");
}
}
That's all you need. No extra classes, no extra methods.
An Exception is a special type of class that can be "thrown" (you can throw it yourself by using the throw keyword, or Java may throw one for you if, for example, you try to access an array index that does not exist or try to perform some operation on a null). A thrown exception will "unwrap" your call stack ("escaping" from each function call) until your program finally terminates. Unless you catch it, which is exactly what the syntax above does.
So if you were writing a function a() that called a function b() that called a function c() and c() threw an exception, but the exception was not caught in b() or c(), you could still catch it in a():
void a() {
try {
b();
catch (SomeExceptionClass e) {
// Handle
}
}
That said, if it is possible to prevent an exception from being thrown in the first place, that is often a better idea. In your particular case, this would be possible since all arrays in Java know their own length:
public static void doingSomething(){
if (i >= something.length) {
System.out.println("Method Halted!, continuing doing the next thing");
} else {
if (something[i] >= something_else) { ... }
}
}
Hmm.. I think you are a little bit confused. You don't catch a method with try catch blocks. You catch Exceptions. Exceptions are more like things.
This alone (note the capital "A" of ArrayOutOfBoundsException) will prevent your program to terminate even if that Exception is thrown. You don't need to declare a "arrayOutOfBoundsException()" method.
public static void doingSomething(){
try
{
if(something[i] >= something_else);
}
catch (ArrayOutOfBoundsException e)
{
System.out.println("Method Halted!, continuing doing the next thing");
}
}
Note the little "e"? That's the reference you can use to refer to this Exception. So, you can ask things to this Exceptions using this little local variable. For example, if you want to print where the exception happened, you can do e.printStackTrace(); .
You catch Exceptions, with a try-catch block. Not sure if you can catch methods with this.
public static void myMethod(){
try {
// check for some given condition
}
catch (conditionNotSatisfied e) {
System.out.println("Condition was not satisfied, you tried to do something which is not allowed");
}
}
The 'e' in the catch() is the reference used for referring to an Exception.
Exception refers to this when it wishes to check your given condition and return you a warning or error about the condition not getting satisfied.
I think you mean to have the arrayOutOfBoundsException method throw the exception caused... If i understand correctly:
public static void arrayOutOfBoundsExceptionMethod() throws ArrayIndexOutOfBoundsException {
\\...
\\ code that throws the exception
}
.....
public static void doingSomething(){
try
{
if(something[i] >= something_else);
arrayOutOfBoundsExceptionMethod();
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Method Halted!, continuing doing the next thing");
}
}
Is that what you are asking?
I'm trying to understand what you're asking, your terminology is wrong in places :) If you try and set an index out of bounds, you'll get a built-in exception anyway, ArrayIndexOutOfBoundsException. You can catch this and use this inside the method, or throw it using a class XX throws ArrayIndexOutOfBoundsException declaration in the header of the method, so that the invoking method can catch it (its not required to catch an ArrayIndexOutOfBoundsException as it's a RuntimeException -- i.e., nothing happens if it goes uncaught, it's unchecked.
See this wiki article for more details: http://en.wikibooks.org/wiki/Java_Programming/Throwing_and_Catching_Exceptions.
It is not clear what you mean by "Is it possible to catch a method". In your case, you should write your code as :
if(i < something.length && something[i] >= something_else);
No ArrayOutOfBoundsException is needed.