This question already has answers here:
Java 8 Lambda function that throws exception?
(27 answers)
Closed 7 years ago.
Given this java 8 code
public Server send(String message) {
sessions.parallelStream()
.map(Session::getBasicRemote)
.forEach(basic -> {
try {
basic.sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
});
return this;
}
how do we properly make this IOException be delegated up the stack of the method call? (in nutshell how to make this method throw this IOException ?)
Lambdas in java does not look very friendly to error handling...
My approach would be to sneakily throw it from the lambda, but take care to have the send method declare it in its throws clause. Using the Exceptional class I posted here:
public Server send(String message) throws IOException {
sessions.parallelStream()
.map(Session::getBasicRemote)
.forEach(basic -> Exceptional.from(() -> basic.sendText(message)).get());
return this;
}
This way you're effectively making the compiler "look away" for just a bit, disabling its exception checking at one spot in your code, but by declaring the exception on your send method, you restore the regular behavior for all its callers.
I wrote an extension to the Stream API which allows for checked exceptions to be thrown.
public Server send(String message) throws IOException {
ThrowingStream.of(sessions, IOException.class)
.parallelStream()
.map(Session::getBasicRemote)
.forEach(basic -> basic.sendText(message));
return this;
}
The problem is indeed that all #FunctionalInterfaces used in lambdas do not allow exceptions to be thrown, save for unchecked exceptions.
One solution is using a package of mine; with it, your code can read:
sessions.parallelStream()
.map(Session::getBasicRemote)
.forEach(Throwing.consumer(basic -> basic.sendText(message)));
return this;
Related
This question already has answers here:
Difference between throw and throws in Java? [duplicate]
(3 answers)
Closed 3 years ago.
I saw a video that explains throws and throw as follows:
Throws - is used to delegate/pass on the exception to the caller method.
class test{
void child() throws filenotfoundException{
//////## this method passes the exception to its caller which is main method
File f = new File("abc")
}
public static void main(String[] args) throws filenotfoundException{
//////##this main method passes the exception to its caller which is JVM
}
}
So in the above example, if file 'abc' doesn't exist, and the exception is not handled using try catch in the child method, the child method will pass on the exception to main method.
As the main method doesn't handle the exceptions using try catch, it also throws or passes the exception to its caller method which is JVM.
Is it correct?
Throw - JVM only understands the logic to pick up predefined exceptions. And hence all the user defined exceptions should manually be created using new Exception and then passed on to JVM using throw keyword.
is it right as well?
The explanation is flawed. First, child() as written isn't going to throw a thing. File not found is not an exception so far and wouldn't be unless you tried to open the file for input.
From your code, though, child() could possibly throw the exception, as could main(). Child doesn't, but it's defined that it might.
Throw is how you actually, well, throw the exception. Like this:
void child() throws FileNotFoundException {
File f("garbage");
if (!f.exists()) {
throw new FileNotFoundException("the world is clean as garbage does not exist");
}
}
Your main() doesn't have a try/catch block, but it could:
void main() {
try {
child();
}
catch (FileNotFoundException e) {
// Oh no!
}
}
throws is used in the method signature to tell everyone that "yes, this method throws an Exception of X type, please be wary" while throw is used to actually launch this Exception and abort the execution of the function.
Yes, depending on the exception, and if you catch it or not, it might bubble all the way up to the JVM. Some Exceptions do not cause the execution to abort however. These are known as RuntimeExceptions. The programmer can decide to handle them, or not, using a try/catch block. RuntimeExceptions do not need to be declared in the function signature.
This question already has answers here:
In Java, is using throws Exception instead of throwing multiple specific exceptions good practice?
(15 answers)
Closed 6 years ago.
Final edit due to this question having been marked as duplicate: this question is about the semantics of the throws declaration - the question which is this said to be a duplicate of handles different aspects of throws and none of those 15 answers there gave me the insight of the chosen answer here. Anyway - so let's keep it here as a duplicate.
In Java you have to declare a throws clause and name the exceptions that this method could throw - so the easy way is to just declare
void myMethod(...) throws Exception
or you could be more specific and for example state
void myMethod(...) throws SQLException, NamingException
in case the method may just throw these two.
I understand that it makes a difference whether in a try/catch block I
try { ... } catch (Exception exc) { ... }
or
try { ... } catch (SQLException | NamingException exc) { ... }
because the first will also catch a RuntimeException, the second won't - so this is a difference.
But is there also any difference in declaring throws Exception vs. throws SQLException, NamingException concerning the semantics of the program? The second may be more readable, but I don't see any other difference. Is there any?
But is there also any difference in declaring throws Exception vs. throws SQLException, NamingException
The difference is:
if you declare throws SQLException, NamingException the compiler assures that you have catched exactly these two exceptions. Otherwise you will get a Unhandled exception type ... error.
On the other hand, if you declare throws Exception, the compiler assures that you have catched Exception.
In the second case, you can still catch any other exception which inherits from Exception without getting a compiler error (like "Exception ... never thrown"). However, you must either catch Exception itself or add the throws Exception to the calling method to allow passing the exception further upwards. For example,
private void someMethod() throws Exception {
throw new NumberFormatException("Illegal number format");
}
If this method gets called, you can catch the NumberFormatException, but you also have to either handle the more generic Exception or declare it in the throws clause (and then handle it further up in the call hierarchy):
public void myMethod() {
try {
someMethod();
}catch(NumberFormatException nfe) {
nfe.printStackTrace();
}catch(Exception ex) {
ex.printStackTrace();
}
}
Or:
public void myMethod() throws Exception {
try {
someMethod();
}catch(NumberFormatException nfe) {
nfe.printStackTrace();
}
}
Yes, there is a difference.
When you use the throws declaration of an exception in a method, you do it so you can handle it later (using try{}catch blocks).
When you handle the exception, you might just do the e.printStackTrace(), but that's not really handling it.
Instead, imagine you want to tell your user "You didn't introduce a number, please correct this mistake" and prompt them to introduce a number. You can do this if you throw NumberFormatException in the method you use to read. But if you throw just Exception, you can't know for sure if that was the error or any other exception, and you might have unexpected behaviours because of that.
The difference between two approach lies based on Exception Handling. For example, if you like to handle all exception in same way then, you should opt for first approach. On the other hand, if you like to deal different exception in different manner, you must go for second approach
I would prefer to mention the exceptions explicitly in the function declaration after the throws keyword because then I know how I should handle these exceptions if they occur in the calling code. See the code below for better understanding..
public static void exceptionExample() throws SQlException, NamingException {
}
public static void main(String[] args) throws SQlException, NamingException {
try {
exceptionExample();
exceptionExample();
}
catch(SQlException e){
System.out.println("Sql exception has occured");
}
catch(NamingException e){
System.out.println("Naming Exception has occured");
}
}
If I would not have mentioned throws SQlException , NamingException explicitly in the function and have used only throws Exception then it implies I do not know which exception may occur. In that case in the catch() {...} block I would have used e.printStackTrace which is not really an efficient method of exception handling because user may never know what happened to the application. But here as you can see that I can inform the user that the respective exception has occurred which makes my application more user friendly.
Also Throwing Exception causes the calling code to catch the exceptions which they may not want to handle depending upon the application and all kinds of reasons.
So I would say it depends upon the wit of the programmer on how he/she wants to handle the exceptions efficiently.....
Observable.fromCallable() is great for converting a single function into an Observable. But how do you handle checked exceptions that might be thrown by the function?
Most of the examples I've seen use lambdas and "just work". But how would you do this without lambdas? For example, see the quote below from this great article:
Observable.fromCallable(() -> downloadFileFromNetwork());
It's a one-liner now! It deals with checked exceptions, no more weird Observable.just() and Observable.error() for such easy thing as deferring code execution!
When I attempt to implement the above Observable without a lambda expression, based on other examples I've seen, and how Android Studio auto-completes, I get the following:
Observable.fromCallable(new Func0<File>() {
#Override
public File call() {
return downloadFileFromNetwork();
}
}
But if downloadFileFromNetwork() throws a checked exception, I have to try-catch it and wrap it in a RuntimeException. There's got to be a better way! How does the above lambda support this?!?!
Rather than using a Func0 with Observable.fromCallable(), use Callable. For example:
Observable.fromCallable(new Callable<File>() {
#Override
public File call() throws Exception {
return downloadFileFromNetwork();
}
}
Since Callable's method call() throws Exception, you don't have to wrap your function in a try-catch! This must be what the lambda is using under the hood.
You could also do this to return checked exceptions:
return Observable.fromCallable(() -> {
sharedPreferences.edit()
.putString(DB_COMPANY, LoganSquare.serialize(
CompanyDBTransformation.get(user.getCompany())
))
.apply();
return user;
}).onErrorResumeNext(
throwable -> Observable.error(new CompanySerializationException(throwable))
);
So here I'm serializing taking the IOException risk, and I'm giving back a more descriptive description.
I have some method that uses some resources that should be closed at the end and the method itself and resource closing could throw everything including IO Connection and so on exceptions, some Runtime exceptions and even Errors (everything what inherits Throwable OOM is often case.).I want to handle all Exceptions without losing information and to send/throw the most important exception to the client (supposingly the runtime exceptions/errors?) This is the pattern I use (it's java 1.5 so I can't use resource features from 1.7):
Throwable thr=null;
try {
methodThatCouldThrowCheckedExceptionAndErrorAndRuntimeExcpetion();
log("method succesfully executed.");
} catch (IKnowThisException ikte) {
//Exception will be not lost
log("Method was not executed ,and I can suggest further actions",itke);
thr=ikte;
} catch (Throwable t) {
// This exception will be not lost too
log("Method was not executed ,and I don't know why.",t);
thr=t;
} finally {
try{
// The method below - of course contains the standard null checkers.
closeResourcesMethodThatCouldThrowEverythingToo();
log("resources were closed.");
} catch (IKnowThisEscpetionToo iktet) {
log(iktet);
throw new IllegalStateException("Resources were not closed , because of the known exception and I can suggest some actions" , ijtet);
} catch (Throwable t) {
log(t);
throw new IllegalStateException("Resources were not closed and I don't know why" , t);
}
// in case resources are closed we can re-throw exception from try{} block
if ( thr != null ) {
throw thr;
}
}
But I'm not completely sure it's the best approach .Here a similar approach i sused . But it does not handle unchecked exceptions (do I need to handle them?) Is there a case when I can lost valuable information? In the most examples I found nothing special is done about Errors/RuntimeExcpetions , but I want them logged. Is there a better approach? May be I should construct a more complicated chained exception to keep information compacted?
To preserve all of the errors, it would be best to use a custom exception class, that provides something like ARM's "suppressed exception" collection.
If the method throws an exception, this is the (cause of the) main exception. If closing resources raises additional exceptions, they are added to the main as suppressed exceptions.
If the method completes without failure, but closing resources raises an exception, the first becomes the main exception, and subsequent resource close failures are added to it as suppressed exceptions.
If a resource was intended to have side effects like writing a file or updating a database, the application needs to determine what to do when closing that resource fails. Using a general purpose mechanism that hides those resource closure exceptions would not allow the application to make that determination, and would only be useful in the rare cases where the application doesn't care if any output is actually produced.
I would look at how the compiler rewrites the try-with-resources pattern in Java 1.7. Below is a simple example of the pattern in source level 1.7, followed by a decompiled version with try-with-resources sugaring disabled:
// Original:
public void test() throws IOException {
try (final StringWriter writer = new StringWriter()) {
writer.write("This is only a test.");
}
}
// Decompiled:
public void test() throws IOException {
final StringWriter writer = new StringWriter();
Throwable t = null;
try {
writer.write("This is only a test.");
}
catch (Throwable t2) {
t = t2;
throw t2;
}
finally {
if (writer != null) {
if (t != null) {
try {
writer.close();
}
catch (Throwable t2) {
t.addSuppressed(t2);
}
}
else {
writer.close();
}
}
}
}
Sadly, the addSuppressed() method was only introduced in Java 1.7, but you could create a custom exception class that introduces this behavior, as #erickson suggests in his answer. If only one exception occurs, simply rethrow that one. Otherwise, replace it with the custom exception, wrap the original as the cause, and add any suppressed exceptions that occurred during closing of resources.
As I know, un-checked exception should not be handle. But you can handle by catching broader exception such as "Exception" before finally block.
I suggest you read my blog post Clean Up After Yourself (Grab my Close class) and then
import static com.frischcode.util.Close.close;
// Where ... is any number of things to close (in finally block - naturally).
close(...);
Is there a way to annotate a method so all exceptions thrown are converted to runtime exception automagically?
#MagicAnnotation
// no throws clause!
void foo()
{
throw new Exception("bar")'
}
Project Lombok's #SneakyThrows is probably what you are looking for. Is not really wrapping your exception (because it can be a problem in a lot of cases), it just doesn't throw an error during compilation.
#SneakyThrows
void foo() {
throw new Exception("bar")'
}
You can do this with AspectJ. You declare a joinpoint (in this case invocation of the method foo) and 'soften' the exception.
Edit To elaborate a bit on this:
Say you have the following class Bar:
public class Bar {
public void foo() throws Exception {
}
}
...and you have a test like this:
import junit.framework.TestCase;
public class BarTest extends TestCase {
public void testTestFoo() {
new Bar().foo();
}
}
Then obviously the test is not going to compile. It will give an error:
Unhandled exception type Exception BarTest.java(line 6)
Now to overcome this with AspectJ, you write a very simple aspect:
public aspect SoftenExceptionsInTestCode {
pointcut inTestCode() : execution(void *Test.test*());
declare soft : Exception : inTestCode();
}
The aspect basically says that any code from within a Test (i.e.: a method that starts with "test" in a class that ends in "Test" and returns 'void') that throws an exception should be accepted by the AspectJ compiler. If an exception occurs, it will be wrapped and thrown as a RuntimeException by the AspectJ compiler.
Indeed, if you run this test as part of an AspectJ project from within Eclipse (with AJDT installed) then the test will succeed, whereas without the aspect it won't even compile.
No way to do that, at least for now I use workaround like this (simplified):
#SuppressWarnings({"rawtypes", "unchecked"})
public class Unchecked {
public static interface UncheckedDefinitions{
InputStream openStream();
String readLine();
...
}
private static Class proxyClass = Proxy.getProxyClass(Unchecked.class.getClassLoader(), UncheckedDefinitions.class);
public static UncheckedDefinitions unchecked(final Object target){
try{
return (UncheckedDefinitions) proxyClass.getConstructor(InvocationHandler.class).newInstance(new InvocationHandler(){
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (target instanceof Class){
return MethodUtils.invokeExactStaticMethod((Class) target, method.getName(), args);
}
return MethodUtils.invokeExactMethod(target, method.getName(), args);
}
});
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
And the usage looks like:
import static ....Unchecked.*;
...
Writer w = ...;
unchecked(w).write(str, off, len);
The trick is that interface is "never finished" and everytime I need unchecked method somewhere, I'll wrap that object into unchecked and let IDE generate method signature in interface.
Implementation is then generic (reflective and "slow" but usually fast enough)
There are some code post-processors and bytecode-weavers but this was not possible (not even aop or other jvm based language) for my current project, so this was "invented".
I think it is possible with bytecode re-engineering, customized compiler or perhaps aspect oriented programming1. In the contrary to Java, C# has only unchecked exceptions2.
May I ask why you want to suppress the checked exceptions?
1 according to Maarten Winkels this is possible.
2 and they are thinking about introducing checked ones, according to some Channel 9 videos.
Edit: For the question: It is possible in the sense that you can annotate your methods to flag them to be a candidate for checked exception suppression. Then you use some compile time or runtime trick to apply the actual suppression / wrapping.
However, as I don't see the environment around your case, wrapping an exception in these ways might confuse the clients of that method - they might not be prepared to deal with a RuntimeException. For example: the method throws an IOException and your clients catches it as FileNotFoundException to display an error dialog. However if you wrap your exception into a RuntimeException, the error dialog gets never shown and probably it kills the caller thread too. (IMHO).
The Checked exceptions are responsability of the method implementation.
Take very very carefully this fact. if you can do not use workaround artifacts like that.
You can do this in any case via use of the fact that Class.newInstance does not wrap an Exception thrown by the no-arg constructor in an InvocationTargetException; rather it throws it silently:
class ExUtil {
public static void throwSilent(Exception e) { //NOTICE NO THROWS CLAUSE
tl.set(e);
SilentThrower.class.newInstance(); //throws silently
}
private static ThreadLocal<Exception> tl = new ThreadLocal<Exception>();
private static class SilentThrower {
SilentThrower() throws Exception {
Exception e = tl.get();
tl.remove();
throw e;
}
}
}
Then you can use this utility anywhere:
ExUtil.throwSilent(new Exception());
//or
try {
ioMethod();
} catch (IOException e) { ExUtil.throwSilent(e); }
By the way, this is a really bad idea :-)
I use the completion / template system of Eclipse to wrap any block of code easily.
Here is my template :
try { // Wrapp exceptions
${line_selection}${cursor}
} catch (RuntimeException e) { // Forward runtime exception
throw e;
} catch (Exception e) { // Wrap into runtime exception
throw new RuntimeException(
"Exception wrapped in #${enclosing_method}",
e);
}