try-catch arround callback - java

public class Test {
public static void main(String[] args) {
try {
doSomething(new TestCallback() {
#Override
public void doCallback() {
throw new NullPointerException();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static void doSomething(TestCallback callback){
callback.doCallback();
}
interface TestCallback {
public void doCallback();
}
}
RESULT:
java.lang.NullPointerException
at managers.concurrency.Test$1.doCallback(Test.java:11)
at managers.concurrency.Test.doSomething(Test.java:20)
at managers.concurrency.Test.main(Test.java:8)
In the above code we will get NullPointerException because the callback code is executed in the different part of stack. Is there a way to catch the such exceptions locally?

You are already catching the exception. Try something as follows -
try {
doSomething(new TestCallback() {
#Override
public void doCallback() {
throw new NullPointerException();
}
});
} catch (Exception e) {
System.out.println("Exception caught !!!");
}
Output:
Exception caught !!!

Related

how to avoid Infinite Recursion in a non-return method with Try catch

public class Sample {
public static void main(String[] args) {
method();
}
public static void method()
{
try {
System.out.println("function");
throw new StaleElementReferenceException("thih sexception occured");
}
catch (StaleElementReferenceException e) {
method();
}
catch (Exception e) {
System.out.println("AssertFail");
}
}
}
how to avoid Infinite Recursion in a non-return method with Try catch...For Example this code below...when the StaleElementException Occurs only once i want to execute "functions after Exception , if the Stale Element occurs the second time i want it to go to Exception catch and print Assert fail..how?
public class Sample {
public static void main(String[] args) {
method(false);
}
public static void method(boolean calledFromCatchBlock)
{
try {
System.out.println("function");
if(!calledFromCatchBlock) {
throw new StaleElementReferenceException("thih sexception occured");
} else {
throw new Exception();
}
} catch (StaleElementReferenceException e) {
method(true);
} catch (Exception e) {
System.out.println("AssertFail");
}
}
}
You should store somehow the state when you throw an exception (e.g. a boolean flag) outside method(), check this state and throw modified exception next time:
private static boolean alreadyThrown = false;
public static void method()
{
try {
System.out.println("function");
if (alreadyThrown) {
throw new RuntimeException("another exception occured");
} else {
alreadyThrown = true;
throw new StaleElementReferenceException("this exception occured");
}
}
catch (StaleElementReferenceException e) {
method();
}
catch (Exception e) {
System.out.println("AssertFail");
}
}
Or you could provide some argument to the method(int arg) and check its value in a similar way:
public static void main(String[] args) {
method(1);
}
public static void method(int arg)
{
try {
System.out.println("function");
if (arg > 1) {
throw new RuntimeException("another exception occured");
} else {
throw new StaleElementReferenceException("this exception occured");
}
}
catch (StaleElementReferenceException e) {
method(arg + 1);
}
catch (Exception e) {
System.out.println("AssertFail");
}
}

How to regroup catch finally into one method in java 8?

New to java 8, I would like to optimise my code bellow:
public Response create() {
try{
...
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
public Response update() {
try{
...
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
I have a lot of methods using this same way to catch exceptions and do the same finally, is that possible to replace the bellow common code by a method in java 8? So that I could optimise all my methods who use this common code.
} catch (Exception e) {
codeA;
} finally {
codeB;
}
Depends what you do in the .... You could do something like this:
private Response method(Supplier<Response> supplier) {
try{
return supplier.get();
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
and invoke like:
public Response create() { return method(() -> { ... for create }); }
public Response update() { return method(() -> { ... for update }); }
You could wrap your payload and put it to the separate method. One thing; what do you expect to return on exception catch. This time this is null, but probably you could provide default value.
public static <T> T execute(Supplier<T> payload) {
try {
return payload.get();
} catch(Exception e) {
// code A
return null;
} finally {
// code B
}
}
Client code could look like this:
public Response create() {
return execute(() -> new CreateResponse());
}
public Response update() {
return execute(() -> new UpdateResponse());
}
This could be a generic solution.
//here describe supplier which can throw exceptions
#FunctionalInterface
public interface ThrowingSupplier<T> {
T get() throws Exception;
}
// The wrapper
private <T> T callMethod(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (Exception e) {
//code A
}finally {
// code B
}
}

Why i'm getting this output in exception handling in Java

Can anybody explain to me what is happening here?
Output I'm getting is
generic exception caught
public class TestingString {
static void testCode() throws MyOwnException {
try {
throw new MyOwnException("test exception");
} catch (Exception ex) {
System.out.print(" generic exception caught ");
}
}
public static void main(String[] args) {
try {
testCode();
} catch (MyOwnException ex) {
System.out.print("custom exception handling");
}
}
}
class MyOwnException extends Exception {
public MyOwnException(String msg) {
super(msg);
}
}
You throw the MyOwnException object in the testCode() method, which is caught immediately by catch (Exception ex)
that is the reason why System.out.print(" generic exception caught "); is excuted , which finally leads to the output.
if you want to get the output custom exception handling. You have to throw the exception in testCode like this
public class TestingString {
static void testCode() throws MyOwnException {
try {
throw new MyOwnException("test exception");
} catch (Exception ex) {
System.out.print(" generic exception caught ");
// throw the exception!
throw ex;
}
}
public static void main(String[] args) {
try {
testCode();
} catch (MyOwnException ex) {
System.out.print("custom exception handling");
}
}
}
class MyOwnException extends Exception {
public MyOwnException(String msg) {
super(msg);
}
}
when you catch the exception you can throw it again. In your original code you are not re-throwing the exception, that is why you only got one message.

Is it like reThrowing the same exception?

When i executed this code i got "finally"
public class Tester {
static void method() throws Exception {
throw new Exception();
}
public static void main(String... args) {
try {
method();
} catch (Throwable th) {
try {
new Exception();
} catch (Exception e) {
System.out.print("Exception");
} finally {
System.out.print("finally");
}
}
}
}
Unable to figure out the flow of execution!!
The output of above mentioned code will be
finally
If you're wondering why the output isn't
Exception finally
then it is because in the following line of code
try {
new Exception();
}
you're only declaring a new Exception object, you're not really throwing it.
if you want the output to be Exception finally then you have to throw that object by putting throw new Exception(); instead of new Exception();
The code would then look like:
public class HelloWorld{
static void method() throws Exception{ throw new Exception(); }
public static void main(String... args){
try{method();}
catch(Throwable th)
{
try{ throw new Exception(); }
catch(Exception e){System.out.print("Exception");}
finally{System.out.print("finally");}
}
}
}
Output
Exceptionfinally
The finally block will be executed if there is or not exception thrown in the code try block.

Catched exception is not handle with the correct method

I have the simple code below :
class Test {
public static void main(String[] args) {
Test t = new Test();
try {
t.throwAnotherException();
} catch (AnotherException e) {
t.handleException(e);
}
try {
t.throwAnotherException();
} catch (Exception e) {
System.out.println(e.getClass().getName());
t.handleException(e);
}
}
public void throwAnotherException() throws AnotherException {
throw new AnotherException();
}
public void handleException(Exception e) {
System.out.println("Handle Exception");
}
public void handleException(AnotherException e) {
System.out.println("Handle Another Exception");
}
}
class AnotherException extends Exception {
}
Why the method called in the second catch is the one with the signature void handleException(Exception e) whereas the kind of exception is AnotherException?
Overloaded methods are resolved at compile time, based on formal parameter types, not runtime types.
That means that if B extends A, and you have
void thing(A x);
void thing(B x);
then
B b = new B();
thing(b);
will look for a thing() that takes a B, because the formal type of b is B; but
A b = new B();
thing(b);
will look for a thing() that takes an A, because the formal type of b is A, even though its runtime actual type will be B.
In your code, the formal type of e is AnotherException in the first case, but Exception in the second case. The runtime type is AnotherException in each case.
AnotherException extends Exception, which means that anywhere you use "Exception", using an instance of "AnotherException" will qualify.
You should probably read up on Extending Classes for a more detailed explanation of how this works as it's very important in programming.
I guess you wanted to test which Exception is gonna get caught, right?
Then modify your code to throw just one Exception:
try {
t.throwAnotherException();
} catch (AnotherException e) {
t.handleException(e);
}
catch (Exception e) {
System.out.println(e.getClass().getName());
t.handleException(e);
}
which is working as expected.
Exception is the super class so if you write your catch clause with (Exception e) first it will always gets satisfy and get executed.
to improve your code you can modify your code as written below.
class Test {
public static void main(String[] args) {
Test t = new Test();
try {
t.throwAnotherException();
} catch (AnotherException e) {
t.handleException(e);
}
try {
t.throwAnotherException();
}catch (AnotherException e) {
t.handleException(e);
}catch (Exception e) {
System.out.println(e.getClass().getName());
t.handleException(e);
}
}
public void throwAnotherException() throws AnotherException {
throw new AnotherException();
}
public void handleException(Exception e) {
System.out.println("Handle Exception");
}
public void handleException(AnotherException e) {
System.out.println("Handle Another Exception");
}
}
class AnotherException extends Exception {
}

Categories

Resources