What is the difference between throw e and throw new Exception(e)?difference between throw and throw new...
It took me a lot of time to make this, pls like. (YouTube Comments #1)
How do ISS astronauts "get their stripes"?
How to properly claim credit for peer review?
g++ and clang++ different behaviour with recursive initialization of a static member
When was drinking water recognized as crucial in marathon running?
Why is working on the same position for more than 15 years not a red flag?
Linear regression when Y is bounded and discrete
What type of postprocessing gives the effect of people standing out
Inventor that creates machine that grabs man from future
What can I substitute for soda pop in a sweet pork recipe?
Do commercial flights continue with an engine out?
How to tighten battery clamp?
What is a term for a function that when called repeatedly, has the same effect as calling once?
Use comma instead of & in table
Do my Windows system binaries contain sensitive information?
Why do members of Congress in committee hearings ask witnesses the same question multiple times?
I am on the US no-fly list. What can I do in order to be allowed on flights which go through US airspace?
What do the pedals on grand pianos do?
How to avoid being sexist when trying to employ someone to function in a very sexist environment?
Gnome Lock Screen Terminology
Could quantum mechanics be necessary to analyze some biology scenarios?
Can chords be played on the flute?
How to acknowledge an embarrassing job interview, now that I work directly with the interviewer?
Is there a better way to make addon working on both blender 2.80 and 2.79?
What is the difference between throw e and throw new Exception(e)?
difference between throw and throw new Exception()What is exception wrapping in Java?Differences between HashMap and Hashtable?Catch multiple exceptions at once?How do you assert that a certain exception is thrown in JUnit 4 tests?What is the difference between public, protected, package-private and private in Java?Difference between StringBuilder and StringBufferDifference between wait() and sleep()What is the difference between JDK and JRE?Manually raising (throwing) an exception in PythonCatch multiple exceptions in one line (except block)Why is it faster to process a sorted array than an unsorted array?
try {
//some code here
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
}
What is the difference between throw e
and throw new Exception(e)
try {
//some code here
} catch (IOException e) {
throw new IOException(e);
} catch (Exception e) {
throw new Exception(e);
}
java exception
add a comment |
try {
//some code here
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
}
What is the difference between throw e
and throw new Exception(e)
try {
//some code here
} catch (IOException e) {
throw new IOException(e);
} catch (Exception e) {
throw new Exception(e);
}
java exception
4
throw
is followed by an expression resolving to aThrowable
object.e
is oneThrowable
object expression, and so isnew Exception(e)
. The difference is just about how the throwable object is created.e
is given to you by thecatch
block, andnew Exception(e)
is being created by your code.
– ernest_k
7 hours ago
3
in this example, it is pointless. however, if you want to use your own exception type, you could do catch(Exception e) { throw new MyException(e); } and this could make your exception handling code a lot easier/minimal
– Stultuske
7 hours ago
2
Former re-throws an already existing exception. Latter creates a new exception withe
being the cause (see the documentation). Also called piggybacking. In the stacktrace you then see the exception and later down "caused by" followed by the stacktrace of the other exception.
– Zabuza
40 mins ago
@CodyGrey I don't understand why you closed this. We can withdraw the first linked question: it's completely irrelevant. On the second linked question: I've read all the answers there and haven't found one from which OP could (1) learn the difference between rethrowing and wrapping an exception and (2) understand the absurdness of 2nd snippet
– Andrew Tobilko
35 mins ago
add a comment |
try {
//some code here
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
}
What is the difference between throw e
and throw new Exception(e)
try {
//some code here
} catch (IOException e) {
throw new IOException(e);
} catch (Exception e) {
throw new Exception(e);
}
java exception
try {
//some code here
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
}
What is the difference between throw e
and throw new Exception(e)
try {
//some code here
} catch (IOException e) {
throw new IOException(e);
} catch (Exception e) {
throw new Exception(e);
}
java exception
java exception
edited 4 hours ago
John Conde
186k80372425
186k80372425
asked 7 hours ago
Vinaya NayakVinaya Nayak
11311
11311
4
throw
is followed by an expression resolving to aThrowable
object.e
is oneThrowable
object expression, and so isnew Exception(e)
. The difference is just about how the throwable object is created.e
is given to you by thecatch
block, andnew Exception(e)
is being created by your code.
– ernest_k
7 hours ago
3
in this example, it is pointless. however, if you want to use your own exception type, you could do catch(Exception e) { throw new MyException(e); } and this could make your exception handling code a lot easier/minimal
– Stultuske
7 hours ago
2
Former re-throws an already existing exception. Latter creates a new exception withe
being the cause (see the documentation). Also called piggybacking. In the stacktrace you then see the exception and later down "caused by" followed by the stacktrace of the other exception.
– Zabuza
40 mins ago
@CodyGrey I don't understand why you closed this. We can withdraw the first linked question: it's completely irrelevant. On the second linked question: I've read all the answers there and haven't found one from which OP could (1) learn the difference between rethrowing and wrapping an exception and (2) understand the absurdness of 2nd snippet
– Andrew Tobilko
35 mins ago
add a comment |
4
throw
is followed by an expression resolving to aThrowable
object.e
is oneThrowable
object expression, and so isnew Exception(e)
. The difference is just about how the throwable object is created.e
is given to you by thecatch
block, andnew Exception(e)
is being created by your code.
– ernest_k
7 hours ago
3
in this example, it is pointless. however, if you want to use your own exception type, you could do catch(Exception e) { throw new MyException(e); } and this could make your exception handling code a lot easier/minimal
– Stultuske
7 hours ago
2
Former re-throws an already existing exception. Latter creates a new exception withe
being the cause (see the documentation). Also called piggybacking. In the stacktrace you then see the exception and later down "caused by" followed by the stacktrace of the other exception.
– Zabuza
40 mins ago
@CodyGrey I don't understand why you closed this. We can withdraw the first linked question: it's completely irrelevant. On the second linked question: I've read all the answers there and haven't found one from which OP could (1) learn the difference between rethrowing and wrapping an exception and (2) understand the absurdness of 2nd snippet
– Andrew Tobilko
35 mins ago
4
4
throw
is followed by an expression resolving to a Throwable
object. e
is one Throwable
object expression, and so is new Exception(e)
. The difference is just about how the throwable object is created. e
is given to you by the catch
block, and new Exception(e)
is being created by your code.– ernest_k
7 hours ago
throw
is followed by an expression resolving to a Throwable
object. e
is one Throwable
object expression, and so is new Exception(e)
. The difference is just about how the throwable object is created. e
is given to you by the catch
block, and new Exception(e)
is being created by your code.– ernest_k
7 hours ago
3
3
in this example, it is pointless. however, if you want to use your own exception type, you could do catch(Exception e) { throw new MyException(e); } and this could make your exception handling code a lot easier/minimal
– Stultuske
7 hours ago
in this example, it is pointless. however, if you want to use your own exception type, you could do catch(Exception e) { throw new MyException(e); } and this could make your exception handling code a lot easier/minimal
– Stultuske
7 hours ago
2
2
Former re-throws an already existing exception. Latter creates a new exception with
e
being the cause (see the documentation). Also called piggybacking. In the stacktrace you then see the exception and later down "caused by" followed by the stacktrace of the other exception.– Zabuza
40 mins ago
Former re-throws an already existing exception. Latter creates a new exception with
e
being the cause (see the documentation). Also called piggybacking. In the stacktrace you then see the exception and later down "caused by" followed by the stacktrace of the other exception.– Zabuza
40 mins ago
@CodyGrey I don't understand why you closed this. We can withdraw the first linked question: it's completely irrelevant. On the second linked question: I've read all the answers there and haven't found one from which OP could (1) learn the difference between rethrowing and wrapping an exception and (2) understand the absurdness of 2nd snippet
– Andrew Tobilko
35 mins ago
@CodyGrey I don't understand why you closed this. We can withdraw the first linked question: it's completely irrelevant. On the second linked question: I've read all the answers there and haven't found one from which OP could (1) learn the difference between rethrowing and wrapping an exception and (2) understand the absurdness of 2nd snippet
– Andrew Tobilko
35 mins ago
add a comment |
4 Answers
4
active
oldest
votes
If you don't need to adjust the exception type, you rethrow (throw further) the same instance without any changes:
catch (IOException e) {
throw e;
}
If you do need to adjust the exception type, you wrap e
(as a cause) into a new exception of the type required.
catch (IOException e) {
throw new IllegalArgumentException(e);
}
I consider all other scenarios a code smell. Your second snippet is a good example of it.
Here are answers to the questions that might pop up.
Why would I want to rethrow an exception?
You can let it go. But if it happens, you won't be able to do anything at this level.
When we catch an exception in a method, we are still in that method and have access to its scope (e.g. local variables and their state). Before we rethrow the exception, we can do whatever we need to (e.g. log a message, send it somewhere, make a snapshot of the current state).
Why would I want to adjust an exception?
As a rule of thumb,
Higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction.
Effective Java - 2nd Edition - Item 61: Throw exceptions appropriate to the abstraction
In other words, at some point, an obscure IOException
should be transformed into a perspicuous MySpecificBusinessRuleException
.
I called it "adjusting the exception type", smart guys call it exception translation (exception chaining, in particular).
To make it clear, let's have some folly examples.
class StupidExample1 {
public static void main(String[] args) throws IOException {
try {
throw new IOException();
} catch (IOException e) {
throw new IOException(new IOException(e));
}
}
}
results in a verbose stack trace like
Exception in thread "main" java.io.IOException: java.io.IOException: java.io.IOException
at StupidExample1.main(XXX.java:XX)
Caused by: java.io.IOException: java.io.IOException
... 1 more
Caused by: java.io.IOException
at StupidExample1.main(XXX.java:XX)
which can (and should) be effectively reduced to
Exception in thread "main" java.io.IOException
at StupidExample1.main(XXX.java:XX)
Another one:
class StupidExample2 {
public static void main(String[] args) {
takeString(new String(new String("myString")));
}
static void takeString(String s) { }
}
It's obvious that new String(new String("myString"))
is a wordy version of "myString"
.
add a comment |
catch (IOException e) {
throw e;
}
You will see original exception with original stacktrace only. You wont see this "retrhrow" line in stacktrace so its kind of transparent.
catch (IOException e) {
throw new IllegalStateException(e);
}
You will see created IllegalStateException
and its stacktrace with "caused by" original excetpion information and stacktrace. You are setting (about to be) thrown exception as cause of newly created IOException
. Upper layer will see IllegalStateException
and that will be caugh possible to catch (you wont catch that caching cause exception).
catch (IOException e) {
throw new IOException();
}
You will see only current stacktrace of IOException
creation, no cause added.
add a comment |
This example doesn't make much sense because you're using the same exception here. You're catching an exception yo handle it, if you cannot - rethrow it.
try {
//some code here
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
}
This pattern allows you to change the type of the exception and keep the original exception details as well:
try {
//some code here
} catch (IOException e) {
throw new IllegalStateException(e);
}
This case often happens when you would like to substitute a Checked Exception
with an Unchecked exception
preserving the origination of the issue and keep all the information:
- you cannot handle a
Checked Exception
and you don't want to rethow it to the caller - this exception means something different inside your business domain and should be wrapped
add a comment |
Well basically, throw e
will "re-throw" all original values- also some code-flow, which should be hidden, eg. security reason for instance , if you will re-create exception, you will get - or you can get - another stacktrace in the place.
So, I would say, you have option to mask some data (dont know, you can for example log exceptions into special log, but you will want to pass another diagnostic data into end-user).
Let's check a following a little:
- I created one class as just only simple generator of Exceptions
- another class allows to rethrow or re-create exception
- afterwards, I am just printing stacktrace, compare results
Exception generator
public class ExceptionsThrow {
public static void throwNewException() throws Exception {
throw new Exception("originally thrown message");
}
}
Class for re-throw/ re-create exceptions
public class Exceptions {
public static void reThrowException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw e;
}
}
public static void reCreateNewException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw new Exception(e);
}
}
}
Testing code example:
try {
Exceptions.reThrowException();
} catch (Exception e) {
System.out.println("1st RETHROW");
e.printStackTrace();
System.out.println("===========");
}
try {
Exceptions.reCreateNewException();
} catch (Exception e) {
System.out.println("2nd RECREATE");
e.printStackTrace();
System.out.println("===========");
}
And the output finally:
1st RETHROW
java.lang.Exception: originally thrown message
at test.main.stackoverflow.ExceptionsThrow.throwNewException(ExceptionsThrow.java:5)
at test.main.stackoverflow.Exceptions.reThrowException(Exceptions.java:7)
at test.main.MainTest.main(MainTest.java:110)
java.lang.Exception: java.lang.Exception: originally thrown message===========
2nd RECREATE
at test.main.stackoverflow.Exceptions.reCreateNewException(Exceptions.java:17)
at test.main.MainTest.main(MainTest.java:118)
Caused by: java.lang.Exception: originally thrown message
at test.main.stackoverflow.ExceptionsThrow.throwNewException(ExceptionsThrow.java:5)
at test.main.stackoverflow.Exceptions.reCreateNewException(Exceptions.java:15)
... 1 more
===========
In this case, you can see mostly the same data, but some additional, you can see original message, because I have used the same Exception to built the new one, but you dont need to do it like this, so you can mask original cause, or you dont need to expose the logic of the app, for instance lets check once more example:
- I will take only cause from original exception, but will override the
data - as you can see, newly created exception doesnt contains the full stacktrace, as the
origin
So:
public static void maskException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw new Exception("I will dont tell you",e.getCause());
}
}
And the result:
===========
3rd mask
java.lang.Exception: I will dont tell you
at test.main.stackoverflow.Exceptions.maskException(Exceptions.java:25)
at test.main.MainTest.main(MainTest.java:126)
===========
So, I would say, recreate exception with the same instance is little pointless, but there can be cases, when you want to do it like that- mask data, or another case can be as well if you want to change Exception type - eg. from IO exception to generic Exception, etc.
In real world, I can remember the really often issue, when some web portals, handled exceptions in PHP scripts only by this case of printing, and then usually, when connection with DB was not working correctly, connection strings (including DB address and credentials in plaintext) were visible in the web browser, eg. :)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54982437%2fwhat-is-the-difference-between-throw-e-and-throw-new-exceptione%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
If you don't need to adjust the exception type, you rethrow (throw further) the same instance without any changes:
catch (IOException e) {
throw e;
}
If you do need to adjust the exception type, you wrap e
(as a cause) into a new exception of the type required.
catch (IOException e) {
throw new IllegalArgumentException(e);
}
I consider all other scenarios a code smell. Your second snippet is a good example of it.
Here are answers to the questions that might pop up.
Why would I want to rethrow an exception?
You can let it go. But if it happens, you won't be able to do anything at this level.
When we catch an exception in a method, we are still in that method and have access to its scope (e.g. local variables and their state). Before we rethrow the exception, we can do whatever we need to (e.g. log a message, send it somewhere, make a snapshot of the current state).
Why would I want to adjust an exception?
As a rule of thumb,
Higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction.
Effective Java - 2nd Edition - Item 61: Throw exceptions appropriate to the abstraction
In other words, at some point, an obscure IOException
should be transformed into a perspicuous MySpecificBusinessRuleException
.
I called it "adjusting the exception type", smart guys call it exception translation (exception chaining, in particular).
To make it clear, let's have some folly examples.
class StupidExample1 {
public static void main(String[] args) throws IOException {
try {
throw new IOException();
} catch (IOException e) {
throw new IOException(new IOException(e));
}
}
}
results in a verbose stack trace like
Exception in thread "main" java.io.IOException: java.io.IOException: java.io.IOException
at StupidExample1.main(XXX.java:XX)
Caused by: java.io.IOException: java.io.IOException
... 1 more
Caused by: java.io.IOException
at StupidExample1.main(XXX.java:XX)
which can (and should) be effectively reduced to
Exception in thread "main" java.io.IOException
at StupidExample1.main(XXX.java:XX)
Another one:
class StupidExample2 {
public static void main(String[] args) {
takeString(new String(new String("myString")));
}
static void takeString(String s) { }
}
It's obvious that new String(new String("myString"))
is a wordy version of "myString"
.
add a comment |
If you don't need to adjust the exception type, you rethrow (throw further) the same instance without any changes:
catch (IOException e) {
throw e;
}
If you do need to adjust the exception type, you wrap e
(as a cause) into a new exception of the type required.
catch (IOException e) {
throw new IllegalArgumentException(e);
}
I consider all other scenarios a code smell. Your second snippet is a good example of it.
Here are answers to the questions that might pop up.
Why would I want to rethrow an exception?
You can let it go. But if it happens, you won't be able to do anything at this level.
When we catch an exception in a method, we are still in that method and have access to its scope (e.g. local variables and their state). Before we rethrow the exception, we can do whatever we need to (e.g. log a message, send it somewhere, make a snapshot of the current state).
Why would I want to adjust an exception?
As a rule of thumb,
Higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction.
Effective Java - 2nd Edition - Item 61: Throw exceptions appropriate to the abstraction
In other words, at some point, an obscure IOException
should be transformed into a perspicuous MySpecificBusinessRuleException
.
I called it "adjusting the exception type", smart guys call it exception translation (exception chaining, in particular).
To make it clear, let's have some folly examples.
class StupidExample1 {
public static void main(String[] args) throws IOException {
try {
throw new IOException();
} catch (IOException e) {
throw new IOException(new IOException(e));
}
}
}
results in a verbose stack trace like
Exception in thread "main" java.io.IOException: java.io.IOException: java.io.IOException
at StupidExample1.main(XXX.java:XX)
Caused by: java.io.IOException: java.io.IOException
... 1 more
Caused by: java.io.IOException
at StupidExample1.main(XXX.java:XX)
which can (and should) be effectively reduced to
Exception in thread "main" java.io.IOException
at StupidExample1.main(XXX.java:XX)
Another one:
class StupidExample2 {
public static void main(String[] args) {
takeString(new String(new String("myString")));
}
static void takeString(String s) { }
}
It's obvious that new String(new String("myString"))
is a wordy version of "myString"
.
add a comment |
If you don't need to adjust the exception type, you rethrow (throw further) the same instance without any changes:
catch (IOException e) {
throw e;
}
If you do need to adjust the exception type, you wrap e
(as a cause) into a new exception of the type required.
catch (IOException e) {
throw new IllegalArgumentException(e);
}
I consider all other scenarios a code smell. Your second snippet is a good example of it.
Here are answers to the questions that might pop up.
Why would I want to rethrow an exception?
You can let it go. But if it happens, you won't be able to do anything at this level.
When we catch an exception in a method, we are still in that method and have access to its scope (e.g. local variables and their state). Before we rethrow the exception, we can do whatever we need to (e.g. log a message, send it somewhere, make a snapshot of the current state).
Why would I want to adjust an exception?
As a rule of thumb,
Higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction.
Effective Java - 2nd Edition - Item 61: Throw exceptions appropriate to the abstraction
In other words, at some point, an obscure IOException
should be transformed into a perspicuous MySpecificBusinessRuleException
.
I called it "adjusting the exception type", smart guys call it exception translation (exception chaining, in particular).
To make it clear, let's have some folly examples.
class StupidExample1 {
public static void main(String[] args) throws IOException {
try {
throw new IOException();
} catch (IOException e) {
throw new IOException(new IOException(e));
}
}
}
results in a verbose stack trace like
Exception in thread "main" java.io.IOException: java.io.IOException: java.io.IOException
at StupidExample1.main(XXX.java:XX)
Caused by: java.io.IOException: java.io.IOException
... 1 more
Caused by: java.io.IOException
at StupidExample1.main(XXX.java:XX)
which can (and should) be effectively reduced to
Exception in thread "main" java.io.IOException
at StupidExample1.main(XXX.java:XX)
Another one:
class StupidExample2 {
public static void main(String[] args) {
takeString(new String(new String("myString")));
}
static void takeString(String s) { }
}
It's obvious that new String(new String("myString"))
is a wordy version of "myString"
.
If you don't need to adjust the exception type, you rethrow (throw further) the same instance without any changes:
catch (IOException e) {
throw e;
}
If you do need to adjust the exception type, you wrap e
(as a cause) into a new exception of the type required.
catch (IOException e) {
throw new IllegalArgumentException(e);
}
I consider all other scenarios a code smell. Your second snippet is a good example of it.
Here are answers to the questions that might pop up.
Why would I want to rethrow an exception?
You can let it go. But if it happens, you won't be able to do anything at this level.
When we catch an exception in a method, we are still in that method and have access to its scope (e.g. local variables and their state). Before we rethrow the exception, we can do whatever we need to (e.g. log a message, send it somewhere, make a snapshot of the current state).
Why would I want to adjust an exception?
As a rule of thumb,
Higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction.
Effective Java - 2nd Edition - Item 61: Throw exceptions appropriate to the abstraction
In other words, at some point, an obscure IOException
should be transformed into a perspicuous MySpecificBusinessRuleException
.
I called it "adjusting the exception type", smart guys call it exception translation (exception chaining, in particular).
To make it clear, let's have some folly examples.
class StupidExample1 {
public static void main(String[] args) throws IOException {
try {
throw new IOException();
} catch (IOException e) {
throw new IOException(new IOException(e));
}
}
}
results in a verbose stack trace like
Exception in thread "main" java.io.IOException: java.io.IOException: java.io.IOException
at StupidExample1.main(XXX.java:XX)
Caused by: java.io.IOException: java.io.IOException
... 1 more
Caused by: java.io.IOException
at StupidExample1.main(XXX.java:XX)
which can (and should) be effectively reduced to
Exception in thread "main" java.io.IOException
at StupidExample1.main(XXX.java:XX)
Another one:
class StupidExample2 {
public static void main(String[] args) {
takeString(new String(new String("myString")));
}
static void takeString(String s) { }
}
It's obvious that new String(new String("myString"))
is a wordy version of "myString"
.
edited 4 hours ago
answered 6 hours ago
Andrew TobilkoAndrew Tobilko
27.8k104287
27.8k104287
add a comment |
add a comment |
catch (IOException e) {
throw e;
}
You will see original exception with original stacktrace only. You wont see this "retrhrow" line in stacktrace so its kind of transparent.
catch (IOException e) {
throw new IllegalStateException(e);
}
You will see created IllegalStateException
and its stacktrace with "caused by" original excetpion information and stacktrace. You are setting (about to be) thrown exception as cause of newly created IOException
. Upper layer will see IllegalStateException
and that will be caugh possible to catch (you wont catch that caching cause exception).
catch (IOException e) {
throw new IOException();
}
You will see only current stacktrace of IOException
creation, no cause added.
add a comment |
catch (IOException e) {
throw e;
}
You will see original exception with original stacktrace only. You wont see this "retrhrow" line in stacktrace so its kind of transparent.
catch (IOException e) {
throw new IllegalStateException(e);
}
You will see created IllegalStateException
and its stacktrace with "caused by" original excetpion information and stacktrace. You are setting (about to be) thrown exception as cause of newly created IOException
. Upper layer will see IllegalStateException
and that will be caugh possible to catch (you wont catch that caching cause exception).
catch (IOException e) {
throw new IOException();
}
You will see only current stacktrace of IOException
creation, no cause added.
add a comment |
catch (IOException e) {
throw e;
}
You will see original exception with original stacktrace only. You wont see this "retrhrow" line in stacktrace so its kind of transparent.
catch (IOException e) {
throw new IllegalStateException(e);
}
You will see created IllegalStateException
and its stacktrace with "caused by" original excetpion information and stacktrace. You are setting (about to be) thrown exception as cause of newly created IOException
. Upper layer will see IllegalStateException
and that will be caugh possible to catch (you wont catch that caching cause exception).
catch (IOException e) {
throw new IOException();
}
You will see only current stacktrace of IOException
creation, no cause added.
catch (IOException e) {
throw e;
}
You will see original exception with original stacktrace only. You wont see this "retrhrow" line in stacktrace so its kind of transparent.
catch (IOException e) {
throw new IllegalStateException(e);
}
You will see created IllegalStateException
and its stacktrace with "caused by" original excetpion information and stacktrace. You are setting (about to be) thrown exception as cause of newly created IOException
. Upper layer will see IllegalStateException
and that will be caugh possible to catch (you wont catch that caching cause exception).
catch (IOException e) {
throw new IOException();
}
You will see only current stacktrace of IOException
creation, no cause added.
edited 6 hours ago
answered 7 hours ago
AntoniossssAntoniossss
16.2k12354
16.2k12354
add a comment |
add a comment |
This example doesn't make much sense because you're using the same exception here. You're catching an exception yo handle it, if you cannot - rethrow it.
try {
//some code here
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
}
This pattern allows you to change the type of the exception and keep the original exception details as well:
try {
//some code here
} catch (IOException e) {
throw new IllegalStateException(e);
}
This case often happens when you would like to substitute a Checked Exception
with an Unchecked exception
preserving the origination of the issue and keep all the information:
- you cannot handle a
Checked Exception
and you don't want to rethow it to the caller - this exception means something different inside your business domain and should be wrapped
add a comment |
This example doesn't make much sense because you're using the same exception here. You're catching an exception yo handle it, if you cannot - rethrow it.
try {
//some code here
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
}
This pattern allows you to change the type of the exception and keep the original exception details as well:
try {
//some code here
} catch (IOException e) {
throw new IllegalStateException(e);
}
This case often happens when you would like to substitute a Checked Exception
with an Unchecked exception
preserving the origination of the issue and keep all the information:
- you cannot handle a
Checked Exception
and you don't want to rethow it to the caller - this exception means something different inside your business domain and should be wrapped
add a comment |
This example doesn't make much sense because you're using the same exception here. You're catching an exception yo handle it, if you cannot - rethrow it.
try {
//some code here
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
}
This pattern allows you to change the type of the exception and keep the original exception details as well:
try {
//some code here
} catch (IOException e) {
throw new IllegalStateException(e);
}
This case often happens when you would like to substitute a Checked Exception
with an Unchecked exception
preserving the origination of the issue and keep all the information:
- you cannot handle a
Checked Exception
and you don't want to rethow it to the caller - this exception means something different inside your business domain and should be wrapped
This example doesn't make much sense because you're using the same exception here. You're catching an exception yo handle it, if you cannot - rethrow it.
try {
//some code here
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
}
This pattern allows you to change the type of the exception and keep the original exception details as well:
try {
//some code here
} catch (IOException e) {
throw new IllegalStateException(e);
}
This case often happens when you would like to substitute a Checked Exception
with an Unchecked exception
preserving the origination of the issue and keep all the information:
- you cannot handle a
Checked Exception
and you don't want to rethow it to the caller - this exception means something different inside your business domain and should be wrapped
edited 6 hours ago
answered 6 hours ago
J-AlexJ-Alex
4,37562742
4,37562742
add a comment |
add a comment |
Well basically, throw e
will "re-throw" all original values- also some code-flow, which should be hidden, eg. security reason for instance , if you will re-create exception, you will get - or you can get - another stacktrace in the place.
So, I would say, you have option to mask some data (dont know, you can for example log exceptions into special log, but you will want to pass another diagnostic data into end-user).
Let's check a following a little:
- I created one class as just only simple generator of Exceptions
- another class allows to rethrow or re-create exception
- afterwards, I am just printing stacktrace, compare results
Exception generator
public class ExceptionsThrow {
public static void throwNewException() throws Exception {
throw new Exception("originally thrown message");
}
}
Class for re-throw/ re-create exceptions
public class Exceptions {
public static void reThrowException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw e;
}
}
public static void reCreateNewException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw new Exception(e);
}
}
}
Testing code example:
try {
Exceptions.reThrowException();
} catch (Exception e) {
System.out.println("1st RETHROW");
e.printStackTrace();
System.out.println("===========");
}
try {
Exceptions.reCreateNewException();
} catch (Exception e) {
System.out.println("2nd RECREATE");
e.printStackTrace();
System.out.println("===========");
}
And the output finally:
1st RETHROW
java.lang.Exception: originally thrown message
at test.main.stackoverflow.ExceptionsThrow.throwNewException(ExceptionsThrow.java:5)
at test.main.stackoverflow.Exceptions.reThrowException(Exceptions.java:7)
at test.main.MainTest.main(MainTest.java:110)
java.lang.Exception: java.lang.Exception: originally thrown message===========
2nd RECREATE
at test.main.stackoverflow.Exceptions.reCreateNewException(Exceptions.java:17)
at test.main.MainTest.main(MainTest.java:118)
Caused by: java.lang.Exception: originally thrown message
at test.main.stackoverflow.ExceptionsThrow.throwNewException(ExceptionsThrow.java:5)
at test.main.stackoverflow.Exceptions.reCreateNewException(Exceptions.java:15)
... 1 more
===========
In this case, you can see mostly the same data, but some additional, you can see original message, because I have used the same Exception to built the new one, but you dont need to do it like this, so you can mask original cause, or you dont need to expose the logic of the app, for instance lets check once more example:
- I will take only cause from original exception, but will override the
data - as you can see, newly created exception doesnt contains the full stacktrace, as the
origin
So:
public static void maskException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw new Exception("I will dont tell you",e.getCause());
}
}
And the result:
===========
3rd mask
java.lang.Exception: I will dont tell you
at test.main.stackoverflow.Exceptions.maskException(Exceptions.java:25)
at test.main.MainTest.main(MainTest.java:126)
===========
So, I would say, recreate exception with the same instance is little pointless, but there can be cases, when you want to do it like that- mask data, or another case can be as well if you want to change Exception type - eg. from IO exception to generic Exception, etc.
In real world, I can remember the really often issue, when some web portals, handled exceptions in PHP scripts only by this case of printing, and then usually, when connection with DB was not working correctly, connection strings (including DB address and credentials in plaintext) were visible in the web browser, eg. :)
add a comment |
Well basically, throw e
will "re-throw" all original values- also some code-flow, which should be hidden, eg. security reason for instance , if you will re-create exception, you will get - or you can get - another stacktrace in the place.
So, I would say, you have option to mask some data (dont know, you can for example log exceptions into special log, but you will want to pass another diagnostic data into end-user).
Let's check a following a little:
- I created one class as just only simple generator of Exceptions
- another class allows to rethrow or re-create exception
- afterwards, I am just printing stacktrace, compare results
Exception generator
public class ExceptionsThrow {
public static void throwNewException() throws Exception {
throw new Exception("originally thrown message");
}
}
Class for re-throw/ re-create exceptions
public class Exceptions {
public static void reThrowException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw e;
}
}
public static void reCreateNewException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw new Exception(e);
}
}
}
Testing code example:
try {
Exceptions.reThrowException();
} catch (Exception e) {
System.out.println("1st RETHROW");
e.printStackTrace();
System.out.println("===========");
}
try {
Exceptions.reCreateNewException();
} catch (Exception e) {
System.out.println("2nd RECREATE");
e.printStackTrace();
System.out.println("===========");
}
And the output finally:
1st RETHROW
java.lang.Exception: originally thrown message
at test.main.stackoverflow.ExceptionsThrow.throwNewException(ExceptionsThrow.java:5)
at test.main.stackoverflow.Exceptions.reThrowException(Exceptions.java:7)
at test.main.MainTest.main(MainTest.java:110)
java.lang.Exception: java.lang.Exception: originally thrown message===========
2nd RECREATE
at test.main.stackoverflow.Exceptions.reCreateNewException(Exceptions.java:17)
at test.main.MainTest.main(MainTest.java:118)
Caused by: java.lang.Exception: originally thrown message
at test.main.stackoverflow.ExceptionsThrow.throwNewException(ExceptionsThrow.java:5)
at test.main.stackoverflow.Exceptions.reCreateNewException(Exceptions.java:15)
... 1 more
===========
In this case, you can see mostly the same data, but some additional, you can see original message, because I have used the same Exception to built the new one, but you dont need to do it like this, so you can mask original cause, or you dont need to expose the logic of the app, for instance lets check once more example:
- I will take only cause from original exception, but will override the
data - as you can see, newly created exception doesnt contains the full stacktrace, as the
origin
So:
public static void maskException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw new Exception("I will dont tell you",e.getCause());
}
}
And the result:
===========
3rd mask
java.lang.Exception: I will dont tell you
at test.main.stackoverflow.Exceptions.maskException(Exceptions.java:25)
at test.main.MainTest.main(MainTest.java:126)
===========
So, I would say, recreate exception with the same instance is little pointless, but there can be cases, when you want to do it like that- mask data, or another case can be as well if you want to change Exception type - eg. from IO exception to generic Exception, etc.
In real world, I can remember the really often issue, when some web portals, handled exceptions in PHP scripts only by this case of printing, and then usually, when connection with DB was not working correctly, connection strings (including DB address and credentials in plaintext) were visible in the web browser, eg. :)
add a comment |
Well basically, throw e
will "re-throw" all original values- also some code-flow, which should be hidden, eg. security reason for instance , if you will re-create exception, you will get - or you can get - another stacktrace in the place.
So, I would say, you have option to mask some data (dont know, you can for example log exceptions into special log, but you will want to pass another diagnostic data into end-user).
Let's check a following a little:
- I created one class as just only simple generator of Exceptions
- another class allows to rethrow or re-create exception
- afterwards, I am just printing stacktrace, compare results
Exception generator
public class ExceptionsThrow {
public static void throwNewException() throws Exception {
throw new Exception("originally thrown message");
}
}
Class for re-throw/ re-create exceptions
public class Exceptions {
public static void reThrowException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw e;
}
}
public static void reCreateNewException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw new Exception(e);
}
}
}
Testing code example:
try {
Exceptions.reThrowException();
} catch (Exception e) {
System.out.println("1st RETHROW");
e.printStackTrace();
System.out.println("===========");
}
try {
Exceptions.reCreateNewException();
} catch (Exception e) {
System.out.println("2nd RECREATE");
e.printStackTrace();
System.out.println("===========");
}
And the output finally:
1st RETHROW
java.lang.Exception: originally thrown message
at test.main.stackoverflow.ExceptionsThrow.throwNewException(ExceptionsThrow.java:5)
at test.main.stackoverflow.Exceptions.reThrowException(Exceptions.java:7)
at test.main.MainTest.main(MainTest.java:110)
java.lang.Exception: java.lang.Exception: originally thrown message===========
2nd RECREATE
at test.main.stackoverflow.Exceptions.reCreateNewException(Exceptions.java:17)
at test.main.MainTest.main(MainTest.java:118)
Caused by: java.lang.Exception: originally thrown message
at test.main.stackoverflow.ExceptionsThrow.throwNewException(ExceptionsThrow.java:5)
at test.main.stackoverflow.Exceptions.reCreateNewException(Exceptions.java:15)
... 1 more
===========
In this case, you can see mostly the same data, but some additional, you can see original message, because I have used the same Exception to built the new one, but you dont need to do it like this, so you can mask original cause, or you dont need to expose the logic of the app, for instance lets check once more example:
- I will take only cause from original exception, but will override the
data - as you can see, newly created exception doesnt contains the full stacktrace, as the
origin
So:
public static void maskException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw new Exception("I will dont tell you",e.getCause());
}
}
And the result:
===========
3rd mask
java.lang.Exception: I will dont tell you
at test.main.stackoverflow.Exceptions.maskException(Exceptions.java:25)
at test.main.MainTest.main(MainTest.java:126)
===========
So, I would say, recreate exception with the same instance is little pointless, but there can be cases, when you want to do it like that- mask data, or another case can be as well if you want to change Exception type - eg. from IO exception to generic Exception, etc.
In real world, I can remember the really often issue, when some web portals, handled exceptions in PHP scripts only by this case of printing, and then usually, when connection with DB was not working correctly, connection strings (including DB address and credentials in plaintext) were visible in the web browser, eg. :)
Well basically, throw e
will "re-throw" all original values- also some code-flow, which should be hidden, eg. security reason for instance , if you will re-create exception, you will get - or you can get - another stacktrace in the place.
So, I would say, you have option to mask some data (dont know, you can for example log exceptions into special log, but you will want to pass another diagnostic data into end-user).
Let's check a following a little:
- I created one class as just only simple generator of Exceptions
- another class allows to rethrow or re-create exception
- afterwards, I am just printing stacktrace, compare results
Exception generator
public class ExceptionsThrow {
public static void throwNewException() throws Exception {
throw new Exception("originally thrown message");
}
}
Class for re-throw/ re-create exceptions
public class Exceptions {
public static void reThrowException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw e;
}
}
public static void reCreateNewException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw new Exception(e);
}
}
}
Testing code example:
try {
Exceptions.reThrowException();
} catch (Exception e) {
System.out.println("1st RETHROW");
e.printStackTrace();
System.out.println("===========");
}
try {
Exceptions.reCreateNewException();
} catch (Exception e) {
System.out.println("2nd RECREATE");
e.printStackTrace();
System.out.println("===========");
}
And the output finally:
1st RETHROW
java.lang.Exception: originally thrown message
at test.main.stackoverflow.ExceptionsThrow.throwNewException(ExceptionsThrow.java:5)
at test.main.stackoverflow.Exceptions.reThrowException(Exceptions.java:7)
at test.main.MainTest.main(MainTest.java:110)
java.lang.Exception: java.lang.Exception: originally thrown message===========
2nd RECREATE
at test.main.stackoverflow.Exceptions.reCreateNewException(Exceptions.java:17)
at test.main.MainTest.main(MainTest.java:118)
Caused by: java.lang.Exception: originally thrown message
at test.main.stackoverflow.ExceptionsThrow.throwNewException(ExceptionsThrow.java:5)
at test.main.stackoverflow.Exceptions.reCreateNewException(Exceptions.java:15)
... 1 more
===========
In this case, you can see mostly the same data, but some additional, you can see original message, because I have used the same Exception to built the new one, but you dont need to do it like this, so you can mask original cause, or you dont need to expose the logic of the app, for instance lets check once more example:
- I will take only cause from original exception, but will override the
data - as you can see, newly created exception doesnt contains the full stacktrace, as the
origin
So:
public static void maskException() throws Exception {
try {
ExceptionsThrow.throwNewException();
} catch (Exception e) {
throw new Exception("I will dont tell you",e.getCause());
}
}
And the result:
===========
3rd mask
java.lang.Exception: I will dont tell you
at test.main.stackoverflow.Exceptions.maskException(Exceptions.java:25)
at test.main.MainTest.main(MainTest.java:126)
===========
So, I would say, recreate exception with the same instance is little pointless, but there can be cases, when you want to do it like that- mask data, or another case can be as well if you want to change Exception type - eg. from IO exception to generic Exception, etc.
In real world, I can remember the really often issue, when some web portals, handled exceptions in PHP scripts only by this case of printing, and then usually, when connection with DB was not working correctly, connection strings (including DB address and credentials in plaintext) were visible in the web browser, eg. :)
edited 6 hours ago
answered 6 hours ago
xxxvodnikxxxxxxvodnikxxx
90011027
90011027
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54982437%2fwhat-is-the-difference-between-throw-e-and-throw-new-exceptione%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
throw
is followed by an expression resolving to aThrowable
object.e
is oneThrowable
object expression, and so isnew Exception(e)
. The difference is just about how the throwable object is created.e
is given to you by thecatch
block, andnew Exception(e)
is being created by your code.– ernest_k
7 hours ago
3
in this example, it is pointless. however, if you want to use your own exception type, you could do catch(Exception e) { throw new MyException(e); } and this could make your exception handling code a lot easier/minimal
– Stultuske
7 hours ago
2
Former re-throws an already existing exception. Latter creates a new exception with
e
being the cause (see the documentation). Also called piggybacking. In the stacktrace you then see the exception and later down "caused by" followed by the stacktrace of the other exception.– Zabuza
40 mins ago
@CodyGrey I don't understand why you closed this. We can withdraw the first linked question: it's completely irrelevant. On the second linked question: I've read all the answers there and haven't found one from which OP could (1) learn the difference between rethrowing and wrapping an exception and (2) understand the absurdness of 2nd snippet
– Andrew Tobilko
35 mins ago