Is it like reThrowing the same exception? - java

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.

Related

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.

java 8 handling custom exception when using Collectors.toMap

Is there any support for handling custom exception inside the Collectors.toMap.
I am calling a method inside the Collector.toMap which throws MyException. Can it be rethrown in the calling function pupulateValues()? For demonstration I used below code to rethrow MyException but couldn't get through. My objective is to handle MyException in main method.
public static void main(String[] args){
try {
pupulateValues();
} catch (MyException e) {
// do something
e.printStackTrace();
}
}
private static void pupulateValues() throws MyException{
Map<String,String> map = new HashMap<>();
map.put("asdf", "asdf");
map.put("ss", "fff");
map.put("aaaaaa", "aaaaaaa");
Map<String,String> map2=map.entrySet().stream().collect(
Collectors.toMap(entry->entry.getKey(),entry-> {
try {
return getCert(entry.getValue());
} catch (MyException e) {
// TODO Auto-generated catch block
throw new MyException();
}}));
}
static String getCert(String val) throws MyException {
if(val == null) {
throw new MyException("Some exception");
}
return val;
}
You have a few options:
make MyException an unchecked exception
wrap it: catch (MyException e) { throw new RuntimeException(e); }
trick the compiler:
https://stackoverflow.com/a/19757456/829571
https://stackoverflow.com/a/31470959/829571
https://github.com/jOOQ/jOOL#orgjooqlambdaunchecked

Is "precise rethrow with a final exception" working in Java SE 8?

public class TestException extends except2 {
public static void main(String[] args)throws Exception {
try {
try {
throw new TestException();
}
catch (final TestException e){
}
throw new except2();
}
catch (TestException a){
}
catch (Exception e){
throw e;
}
}
public TestException(){
}
}
class except2 extends Exception{
}
Hi all,
my JDK version is 8u45 which is latest one now.
I'm wondering that is "precise rethrow with a final exception" still working in SE 8?
As the code, if I take the "throws Exception" off it'll be compilation error, but it should be able to be ignored according to "precise rethrow with a final exception" function of SE7.
Another question is that we all know if there's an exception happened in the nested try box, we should still throw it out to outer catch box to avoid compilation error, I originally figured that we only need to throw an exception of any types & it'll do, so is my test result, I think it's to let compiler know that there's an exception in try box & catch box got it, too.
but if I alter it like the following code:
public class TestException extends except2 {
public static void main(String[] args)throws Exception {
try {
try {
throw new ArithmeticException();
} catch (final TestException e){
throw e;
}
} catch (TestException a){
} catch (Exception e){
throw e;
}
}
}
the (final TestException e) part will be compilation error with the message:
"the Exception "com.xxx.TestException" is never thrown in the corresponding try block",
and I'm confused because if nested catch block can't handle the exception, it shall goes to outer.
Then if I throw an ArithmeticException in the end of outer try block like this:
try {
try {
throw new TestException();
}
catch (final TestException e){
System.out.println("d");
}
throw new ArithmeticException();
}
catch (TestException a){
}
catch (Exception e){
throw e;
}
Same error to the outer catch box catch (TestException a){}
Why is that?
it should be caught by (Exception e) block.
If I can't throw different types of exception from the first exception of nested try block, why could I throw except2 in the first paragraph of code?
This is Oracles example for the feature, and it still works with Java 8:
static class FirstException extends Exception { }
static class SecondException extends Exception { }
public void rethrowException(String exceptionName)
throws FirstExceptio, SecondException // Since J7 no "Exception" needed
{
try {
if (exceptionName.equals("First")) {
throw new FirstException();
} else {
throw new SecondException();
}
} catch (Exception e) {
throw e; // effective final (i.e. not assigned)
}
}
This is described in the second half of this Oracle document. Your examples are all not really related to it. Especially not the one where you have a more specific and a general catch. This is explicitly mentioned in the document as not working.
Your first block would work if you use except2 (I renamed it to BaseException) which is the more specific one like this:
public class TestException extends BaseException {
public static void main(String[] args) {
try {
try {
throw new TestException();
}
catch (final BaseException e){
throw e; // this is defined as BaseEx, will fail on Java 6
}
}
catch (TestException a){ // this knows that no BaseEx is expected
}
}
public TestException(){
}
}
class BaseException extends Exception { }
As you can see, the main() method does not need to throw Exception anymore since the second catch block was sufficient.
Your first piece of code can be shortened to
class TestException extends except2 throws Exception {
public static void main(String[] args) {
try {
throw new except2(); // this
} catch (TestException a) {
} catch (Exception e) {
throw e;
}
}
public TestException() {
}
}
class except2 extends Exception {
}
You're throwing an except2. A TestException is an except2, but an except2 is not necessarily a TestException. The first catch block cannot handle the except2 exception. So the second one must. Since it further throws that exception, and that exception is necessarily checked, you need to have a throws clause.
Your second piece of code
class TestException extends except2 {
public static void main(String[] args) throws Exception {
try {
try {
throw new ArithmeticException();
} catch (final TestException e) { // nothing above throws a TestException
throw e;
}
} catch (TestException a) {
}
catch (Exception e) {
throw e;
}
}
}
Is trying to catch a TestException in the nested try block. But since TestException is a checked exception, the compiler can and does check if it can be thrown in that block. In your case, it can't. So it complains that's it useless to try and catch it.
Finally, in your last snippet
class TestException extends except2 {
public static void main(String[] args) throws Exception {
try {
try {
throw new TestException();
} catch (final TestException e) {
System.out.println("d");
}
throw new ArithmeticException();
} catch (TestException a) {
} catch (Exception e) {
throw e;
}
}
}
You're throwing and catching a TestException in the nested try-catch statement. So you can reduce the code to
class TestException extends except2 {
public static void main(String[] args) throws Exception {
try {
throw new ArithmeticException();
} catch (TestException a) {
} catch (Exception e) {
throw e;
}
}
}
Which has the same issue as your second piece of code. There is no code path there that can throw a TestException.
Regarding comments, and to simplify the second snippet, the error reduces to
class TestException extends except2 {
public static void main(String[] args) throws Exception {
try {
throw new ArithmeticException();
} catch (final TestException e) { // nothing above throws a TestException
throw e;
}
}
}
You have a catch(TestException) but nothing throws a TestException, so it's useless code which the compiler rejects.
From comments, this is the problem with your cases 2 and 3
// ignore everything around this
try {
// nothing in this block
// can throw a TestException
throw new ArithmeticException();
// this whole catch block is useless code
// Test Exception can never be thrown
} catch (final TestException e){
throw e;
}
// ignore everything around this

catch multiple exceptions at once in java?

import java.io.*;
class West1 extends Exception {
private String msg;
public West1() {
}
public West1(String msg) {
super(msg);
this.msg=msg;
}
public West1(Throwable cause) {
super(cause);
}
public West1(String msg,Throwable cause) {
super(msg,cause);
this.msg=msg;
}
public String toString() {
return msg;
}
public String getMessage() {
return msg;
}
}
public class West {
public static void main(String[] args) {
try {
throw new West1("Custom Exception.....");
}catch(West1 ce) {
System.out.println(ce.getMessage());
//throw new NumberFormatException();
throw new FileNotFoundException();
}catch(FileNotFoundException fne) {
fne.printStackTrace();
}/*catch(NumberFormatException nfe) {
nfe.printStackTrace();
}*/
}
}
In the above code, NumberFormatException is thrown from catch block it compile and run successfully but when FileNotFoundException is thrown from catch block it will not compile. Following Errors are thrown:
West.java:40: error: exception FileNotFoundException is never thrown in body of
corresponding try statement
}catch(FileNotFoundException fne){
West.java:39: error: unreported exception FileNotFoundException; must be caught
or declared to be thrown
throw new FileNotFoundException();
So my question is what is reason behind this behaviour?
NumberFormatException is a RuntimeException, meaning that it's not required to be declared in all methods it may be thrown. This means that, unlike FileNotFoundException, the compiler can not know if it can get thrown in a block or not.
The title implies you are trying to catch multiple exceptions at once, and your code implies you understand that you can have multiple catch blocks for a single try block to catch different types of exceptions. Everything is good so far, but you seem to misunderstand exactly where the try-catch catches errors.
Here is you code. I removed the comments to make it more concise.
public class West {
public static void main(String[] args) {
try {
throw new West1("Custom Exception.....");
} catch(West1 ce) {
System.out.println(ce.getMessage());
throw new FileNotFoundException(); // <-- Must be caught
} catch(FileNotFoundException fne) { // <-- Never thrown
fne.printStackTrace();
}
}
}
The first compiler error is because the catch block that is for catching FileNotFoundException's try block never throws FileNotFoundException. The second compiler error is because FileNotFoundException is a checked exception. Because it is a checked exception your code must either
handle it (by catching it with try-catch)
let everyone know it could throw it (public static void main(String[] args) throws FileNotFoundException { ...).
From the context of your code, you seem to be going with the first option, handling it with try-catch, but you have the catch in the wrong place.
catch blocks don't catch exceptions, try blocks do. catch blocks specify what to do with the actual caught exception.
public class West {
public static void main(String[] args) {
try {
throw new West1("Custom Exception.....");
} catch(West1 ce) {
System.out.println(ce.getMessage());
try {
throw new FileNotFoundException();
} catch(FileNotFoundException fne) {
fne.printStackTrace();
}
}
}
}
Try that instead. Notice how you can have a try instead of a catch. This wouldn't matter if FileNotFoundException wasn't a checked exception.

try-catch arround callback

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 !!!

Categories

Resources