Continue from the next line after getting exception - java

I want to continue with the next line from which error generated,
try{
statement A;
statement B;
statement C;
}
catch(NullPointerException NPE){.....}
Now assume that my statement A throws exception so I want to skip that and continue with B. Don't give my suggestion to put in catch/finally block or any other solution. I just want to know is this possible to skip and continue with next statement?

Yes, it is possible without the finally block.
try{
statement A;
}
catch(NullPointerException NPE){.....}
try{
statement B;
}
catch(NullPointerException NPE){.....}
try{
statement C;
}
catch(NullPointerException NPE){.....}
On the side note, I don't really think this is nice. If you managed to come to the point where you need this kind of flow control, you need to take a step back and rethink your code design.

It is not possible to execute statement B if A throws exception. One way is seperately try/catch block and other way is put other lines into finally block.

If your statements are similar and can be paramerized, use a loop:
for (int i = 0; i < statementCount; i++) {
try {
/** do what you need */
} catch(Exception e) {
}
}
or put it in separate method if it needs more parameters:
public static void main(String[] args) {
for (int i = 0; i < statementCount; i++) {
}
execute(params);
}
public void execute(Object... objects) {
try {
doSomthing(objects[0], objects[1]);
} catch(Exception e) {
}
}
If statements are abolutely different, Java 8 provides interesting solutions: method references and lambdas. So you can play arround with somthing like this:
public static void main(String[] args) {
execute(someObject, YourClass::method);
}
public void execute(Object param, Function<Object, Void> function) {
try {
function.apply(param);
} catch(Exception e) {
}
}

Like darijan already mentioned you could put every single statement into an own try-catch. Or if you know what may cause the exception you can simply check it befor you execute your statements
try{
if(parameterForStatementA != null) {
statementA;
}
if(parameterForStatementB != null) {
statementB;
}
if(parameterForStatementC != null) {
statementC;
}
} catch(Exception e) {
// something unexpected happened
}
Verifying parameters is usually more efficient than catching thrown exceptions

Related

How finally block works?

hello community in my tutorial this week I found out that all threads stop when java gets a runtime error, but in the finally code block this event looks a bit strange.
public class main {
public static void main(String[] args) {
try {
Scanner kb = new Scanner(System.in);
System.out.println("enter number:");
double val = Double.parseDouble(kb.nextLine());
double result = MathUtil.myLog(val);
}
catch (MyException ex) {
System.out.println("Cath:foo");
}
finally {
System.out.println("foo:finally");
}
}
class MathUtil {
public static double myLog(double val)
{
if (val < 0)
throw new MyException();
if(val == 0)
throw new YourException();
return Math.log(val);
}
class MyException extends RuntimeException {
}
class YourException extends RuntimeException {
}
When i execute this code and make an incorrect entry it first executes the finally block and then I get runtimeError.
Works as indented, doesn't matter if catch clause catch an error, finally as it says will execute almost every time. It won't execute only if JVM runs out of memory but it's rare corner case
This works as designed :-) From the documantation from oracle:
'The finally block always executes when the try block exits..'
For me this means the finally block will be executed before the catch block or anything else is executed.

Recursive call in try-catch block to retry N number of times

I have a regular, non-static sendMail method which may occasionally fail. I need to catch any errors and retry the method N number of times. I'm not sure I'm doing the right thing, and there's also a compilation error:
public void sendMail(List<String> params) {
try {
//...
static int retrycount = 0; // static not allowed here (but need to keep static var for recursion)
int maxretries = 3;
}
catch (Exception e) {
log.info(e);
// Recursion to retry
sendMail(params);
retrycount++;
}
}
First of all, is recursion from a try/catch block correct? Also, is there a better way to do this?
I can't make the sendMail method static, there are too many references to it in the existing code.
Your retry will never work in the first place because inside every try block you are setting retrycount to 0.
You'd probably be better off throwing the exception instead of catching it. Then using some kind of a while loop till it completes, maybe with a configurable delay between retries. Or if you're using Spring there is the Retryable annotation.
void someMethod(){
int attempts = 0;
while(attemps <= 3){
try {
sendMail(...);
break;
} catch (Exception e){
attempts++;
// Log failed to send mail or something meaningful, maybe add a delay here?
}
}
}
This solution is much cleaner than using recursion as if you wanted to retry many times, eventually you'd get a stack overflow error. It also keeps the responsbility of the sendMail function simple, and avoids adding complicated retry logic to an otherwise simple method.
Also, if you end up having to make other methods retryable in the same fashion then it would be much easier to abstract away the retry logic into some kind of executor service that handles it all.
What if you just wrapped the code in a retry loop:
public void sendMail(List<String> params) {
for (int attempt = 0; attempt < 3; attempt++)
try {
//...
if (<some success condition>)
return;
}
catch (Exception e) {
log.info(e);
}
}
The standard recursive solution would be to add retryCount as a paremeter.
public void sendMail(List<String> params) {
sendMail(params, 0);
}
private void sendMail(List<String> params, int retryCount) {
try {
//...
int maxRetries = 3;
} catch (Exception e) {
log.info(e);
// Recursion to retry
sendMail(params, retryCount+1);
}
}
A loop would be the more idiomatic way of writing this.
public void sendMail(List<String> params) {
int maxTries = 4;
for (int tryCount=0; tryCount<maxTries; ++tryCount) {
try {
//...
break;
} catch (Exception e) {
log.info(e);
// continue to retry
}
}
}
In the spirit of the original question, the retryCount can be kept as a field within an introduced object. It's easiest (if slightly obscure) to do this with an anonymous inner class.
public void sendMail(List<String> params) {
int maxTries = 4;
new Object() {
int tryCount = 0;
public void sendMail() {
try {
//...
} catch (Exception e) {
log.info(e);
// Recursion to retry
if (tryCount < maxTries) {
++tryCount;
sendMail();
}
}
}
}.sendMail();
}

Return from method, in the "try" block or after "catch" block?

Is there any difference between following two methods?
Which one is preferable and why?
Prg1:
public static boolean test() throws Exception {
try {
doSomething();
return true;
} catch (Exception e) {
throw new Exception("No!");
}
}
Prg2:
public static boolean test() throws Exception {
try {
doSomething();
} catch (Exception e) {
throw new Exception("No!");
}
return true;
}
Consider these cases where you're not returning a constant expression:
Case 1:
public static Val test() throws Exception {
try {
return doSomething();
} catch (Exception e) {
throw new Exception("No!");
}
// Unreachable code goes here
}
Case 2:
public static Val test() throws Exception {
Val toReturn = null;
try {
toReturn = doSomething();
} catch (Exception e) {
throw new Exception("No!");
}
return toReturn;
}
I would prefer the first one. The second is more verbose and might cause some confusion when debugging.
If test() incorrectly returns null, and you see toReturn being initialized to null, you might think the problem is in test() (especially when test() is not just a simple example like this).
Even though it can only return null if doSomething returns null. But that might be hard to see at a glance.
You could then argue that, for consistency's sake, it's better to always use the first form.
Nope there is no difference between both the methods.
It will return true value in both the cases effectively by resuming the flow of the program as soon an and exception is handled.
Catch will be accessed only when an exception occurs.
I'm assuming this is a general question. Otherwise I might comment on other aspects of your method(s).
I think in the case or small methods like these it doesn't really matter. The method is short enough to understand immediately what's going on, what's related to what etc.
However, in the case of longer methods the flow is much easier to follow in the first example. In my opinion. It keeps together related code and related scenarios. When you're reading the method, the normal execution flow is not broken by the catch block, making it more obvious and "fluent".
public static boolean test() throws Exception {
try {
doSomething();
return true;
} catch (Exception e) {
throw new Exception("No!");
}
}
But I won't generalize this for all methods; it's all about the context.
There is no difference, but the first Prg1 is faster than the Prg2.

Optional exception catching

Is it possible to make an exception that is optional to be caught?
In other words, an exception that can either:
be caught in a try-catch block
or skipped if no try-catch block exists for it
To visualize, I have a ReportedException, which is just a plain subclass of RuntimeException, and want to be able to catch it when it's needed:
try
{
hideWindow();
}
catch (ReportedException ex)
{
// Window could not be hidden.
// Exception has already been caught and logged by parseInput(),
// and now we're going to do something more.
printAdditionalErrorMessage();
}
Note: I edited the above example to better fit my question.
or skip catching if the result is irrelevant:
hideWindow(); // We don't care if there was an error or not.
openAnotherWindow();
I know I can leave the catch block empty and have the same thing as above, but I use ReportedException very often and it would make my code highly unreadable.
If it's impossible (I suspect it is), what alternative/walkaround would you recommend?
P.S. The method names used in the examples are just foo's and bar's.
EDIT: I know I don't need to catch RuntimeExceptions. What I want is to ignore them if they occur.
Exceptions should be used for exceptional situations.
From your example, if the window not being hidden is a typical event, it shouldn't throw an exception. If that is your function, then use a return value to indicate whether it was successful instead of throwing an exception. Then you can safely ignore the return value when you don't care if it succeeded or not.
If you do not have control over that method, then you can wrap it in another method that catches the exception and turns it into a return value. E.g.
private boolean tryHideWindow() {
try {
hideWindow();
}
catch (ReportedException ex) {
return false;
}
return true;
}
If you need some parameters of the exception to determine what to do, then you could return the exception instead.
private static class MyReturnType {
private final Throwable thrown;
private final OrigRtnType returnVal;
public MyReturnType(Throwable thrown) {
this.thrown = thrown;
this.returnVal = null;
}
public MyReturnType(OrigRtnType returnVal) {
this.thrown = null;
this.returnVal = returnVal
}
public boolean wasExceptionThrown() {
return thrown != null;
}
}
private MyReturnType tryHideWindow() {
try {
OrigRtnType returnVal = hideWindow();
}
catch (ReportedException ex) {
return new MyReturnType(ex);
}
return new MyReturnType(returnVal);
}
This is an answer to your question, but it is not necessarily a good idea. As others will doubless comment, using exceptions for program flow is less than ideal.
I'm a little fuzzy on how to use ThreadLocal (and there are apt to be some other tupos), but something like this:
public class IgnorableException {
static class DontIgnoreCount {
int count;
}
// Thread local variable containing each thread's ID
private static final ThreadLocal<DontIgnoreCount> dontIgnoreCount =
new ThreadLocal<DontIgnoreCount>();
static void incrementDontIgnore() {
DontIgnoreCount counter = dontIgnoreCount.get();
if (counter == null) {
counter = new DontIgnoreCount();
dontIgnoreCount.set(counter);
}
counter.count++;
}
static void decrementDontIgnore() {
DontIgnoreCount counter = dontIgnoreCount.get();
// Must not be null here
counter.count--;
static bool shouldSignal() {
DontIgnoreCount counter = dontIgnoreCount.get();
return counter.count > 0;
}
}
To use, invoke DontIgnoreCount.incrementIgnoreCount() early in try range, and DontIgnoreCount.decrementIgnoreCount() late in finally range.
When signalling an exception that follows this protocol, only signal it if shouldSignal returns true.
void iWannaCatchException() {
try {
IgnornableException.incrementDontIgnore();
int x = someOptionallySignallingMethod();
}
catch (...) {
...
}
finally {
IgnorableException.decrementDontIgnore();
}
}
void iDontWannaCatchException() {
int x = someOptionallySignallingMethod();
}
int someOptionallySignallingMethod() {
if (somethingBad) {
if (IgnorableException.shouldSignal()) {
throw new BadException();
}
}
return 42;
}
Note that not shown above are any throws clauses you'd have to add to keep the compiler happy. This mechanism would not remove the need for those.
You could also inplement a delegate/observer scheme, replacing the simple counter with a stack of observer objects, and pass a message to the observer vs throwing the exception. But this, by itself (without coupled exceptions/try ranges) would not allow blowing away the stack to the appropriate recovery point.
It sounds like you want to use exceptions for flow control, rather than for reporting truly exceptional cases.
Using exceptions for flow control is typically frowned upon. The common approach is to return a success/failure indication as the return value of the function.
You can use something like this:
try{
hideWindow();
}catch (ReportedException ex){
// ingore
}catch (NullPointerException ex){
killWindow();
}finally {
//to do something more.
}

return statement and exception in try block in java

public class Test2 {
public static void main(String args[]) {
System.out.println(method());
}
public static int method() {
try {
throw new Exception();
return 1;
} catch (Exception e) {
return 2;
} finally {
return 3;
}
}
}
in this problem try block has return statement and throws exception also...
its output is COMPILER ERROR....
we know that finally block overrides the return or exception statement in try/catch block...
but this problem has both in try block...
why the output is error ?
Because your return statement is unreachable - the execution flow can never reach that line.
If the throw statement was in an if-clause, then the return would be potentially reachable and the error would be gone. But in this case it doesn't make sense to have return there.
Another important note - avoid returning from the finally clause. Eclipse compiler, for example, shows a warning about a return statement in the finally clause.
The compiler exception come from, like my Eclipse dude says
Unreachable code Test2.java line 11 Java Problem
The return statement of your main code block will never be reached, as an exception is thrown before.
Alos notice the return statement of your finally block is, at least, a design flaw, like Eclipse once again says
finally block does not complete normally Test2.javajava line 14 Java Problem
Indeed, as a finally block is only here to provide some clean closing, it is not expected to return something that would override the result normally returned by the method.
The throw new Exception() will be called no matter what, so anything within the try block that follows the throw is Unreachable Code. Hence the Error.
public class Test2 {
public static void main(String args[]) {
System.out.println(method());
}
public static int method() {
try {
throw new Exception();
return 1; //<<< This is unreachable
} catch (Exception e) {
return 2;
} finally {
return 3;
}
}
}
It should eventually return 3.
Because 'return' keyword within try block is unreachable, that's why you are getting compile-time error. Omit that 'return' keyword from try block, and then run your program, your will successfully compile.

Categories