I have the following Java code (that I thought was OK) but the IDE is warning me that "IOExcpetion e is immediately rethrown."
I'm new to exception handling in Java, and I wasn't aware there was anything wrong with doing that.
From what I'm reading, it looks like my other options is to simply delete the catch block and replace it with a finally block... but then it warns that the finally block is empty.
I don't have any ideas on what I should do differently.
private InputStream getFlutterAssetAsInputStream(String fromAsset) throws IOException {
String assetPath = binding
.getFlutterAssets()
.getAssetFilePathBySubpath(fromAsset, PACKAGE_NAME);
try {
return binding.getApplicationContext().getAssets().open(assetPath);
} catch (IOException e) {
throw e;
}
}
This
try {
return binding.getApplicationContext().getAssets().open(assetPath);
}
catch (IOException e) {
throw e;
}
is functionally equivalent to this:
return binding.getApplicationContext().getAssets().open(assetPath);
Your IDE is telling you that your try-catch is pointless. It does nothing.
So what do you want to do?
Pass the exception on to your caller? In which case get rid of the try-catch
Signal a different exception on to the caller - maybe one with a more appropriate error message for the specific circumstances? Then make and throw a new exception object with a better error message.
Do something to handle the situation - at the very least, maybe display an error message? Log the event to enable debugging? Then write code in the catch-block to do that. And then you have to decide what happens next.
Fundamentally, this is a design issue. IO errors happen. So how does this method that you're writing want to handle IO errors?
Related
In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.
Is there a more elegant way of doing this? Perhaps an API call that will reveal this?
Here's some rough code of what I'm talking about:
Throwable t = null;
try {
stream.write(buffer);
} catch(IOException e) {
t = e; //Need to save this exception for finally
throw e;
} finally {
try {
stream.close(); //may throw exception
} catch(IOException e) {
//Is there something better than saving the exception from the exception block?
if(t!=null) {
//propagate the read exception as the "cause"--not great, but you see what I mean.
throw new IOException("Could not close in finally block: " + e.getMessage(),t);
} else {
throw e; //just pass it up
}
}//end close
}
Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.
Maybe something like Thread.getPendingException() or something similar? For that matter, is there an elegant solution in other languages?
This question actually spawned from comments in another question that raised an interesting question.
Your idea about setting a variable outside the scope of the try/catch/finally is correct.
There cannot be more than one exception propagating at once.
Instead of using a Boolean flag, I would store a reference to the Exception object.
That way, you not only have a way to check whether an exception occurred (the object will be null if no exception occurred), but you'll also have access to the exception object itself in your finally block if an exception did occur. You just have to remember to set the error object in all your catch blocks (iff rethrowing the error).
I think this is a missing C# language feature that should be added. The finally block should support a reference to the base Exception class similar to how the catch block supports it, so that a reference to the propagating exception is available to the finally block. This would be an easy task for the compiler, saving us the work of manually creating a local Exception variable and remembering to manually set its value before re-throwing an error, as well as preventing us from making the mistake of setting the Exception variable when not re-throwing an error (remember, it's only the uncaught exceptions we want to make visible to the finally block).
finally (Exception main_exception)
{
try
{
//cleanup that may throw an error (absolutely unpredictably)
}
catch (Exception err)
{
//Instead of throwing another error,
//just add data to main exception mentioning that an error occurred in the finally block!
main_exception.Data.Add( "finally_error", err );
//main exception propagates from finally block normally, with additional data
}
}
As demonstrated above... the reason that I'd like the exception available in the finally block, is that if my finally block did catch an exception of its own, then instead of overwriting the main exception by throwing a new error (bad) or just ignoring the error (also bad), it could add the error as additional data to the original error.
You could always set a boolean flag in your catch(es). I don't know of any "slick" way to do it, but then I'm more of a .Net guy.
Use logging...
try {
stream.write(buffer);
} catch(IOException ex) {
if (LOG.isErrorEnabled()) { // You can use log level whatever you want
LOG.error("Something wrong: " + ex.getMessage(), ex);
}
throw ex;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not close in finally block", ex);
}
}
}
}
In vb.net, it's possible to use a "Catch...When" statement to grab an exception to a local variable without having to actually catch it. This has a number of advantages. Among them:
If nothing is going to 'ultimately' catch the exception, an unhandled exception trap will be fired from the spot of the original exception. Much nicer than having the debugger trap at the last rethrow, especially since information that might be needed for debugging won't yet have gone out of scope or been swept up by 'finally' statements.
Although a rethrow won't clear the stack trace the way "Throw Ex" would, it will still often jinx the stack trace. If the exception isn't caught, the stack trace will be clean.
Because this feature is unsupported in vb, it may be helpful to write a vb wrapper to implement the code in C (e.g. given a MethodInvoker and an Action(Of Exception), perform the MethodInvoker within a "Try" and the Action in a "Finally".
One interesting quirk: it's possible for the Catch-When to see an exception which will end up getting overwritten by a Finally-clause exception. In some cases, this may be a good thing; in other cases it may be confusing. In any event, it's something to be aware of.
I came across a code written by someone with Assert.fail("some text") in a catch block. This is my code:
try {
//WebDriver code here which interacts with WebElements
//When an exception occurs in this try block, it will be caught in
//the catch and further catch block has Assert.fail()
} catch (Exception e) {
Assert.fail("failed to click 'Webelement' ");
}
I somehow felt this is not right way to do it. Am i wrong?
Note: Not exactly a duplicate of Is Assert.Fail() considered bad practice , As i am not expecting any Exception. If any exception occurs i need to fail the test case
Though it's syntactically not incorrect. But you should preferably rephrase your tests to use expectedException instead and be specific about the exception is thrown as well. For e.g. :
If your method fromTest() when called with "test" as an argument could throw an NumberFormatException, then your test definition for such behaviour should be :
#Test(expectedExceptions = NumberFormatException.class)
public void testMethod() {
System.out.println("About to throw an exception!");
fromTest("test");
}
Note: If you believe that the exception may so happen within your test execution itself instead of any other method being called from it. I would suggest to not catch it. Let it fail and then you shall fix it.
This question already has answers here:
When to catch the Exception vs When to throw the Exceptions?
(8 answers)
Closed 3 years ago.
So I have two general questions about java in general. The first is when would one use a try/catch in the body of the method versus using throws exception in declaring the method? Here is a little demonstration of what I mean. This:
public void whileChatting() throws IOException{}
versus
public void closeConnection() {
try {
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
And then my second question is when does one know what type of exception to either catch or throw? By that I mean exceptions such as IOException or EOFException and so on...
If there's a good link someone could send me teaching all this (being that it's probably more complicated than I think) I would be just as grateful as if you answered it.
Thanks.
Throwing Exceptions
In your first example,
public void whileChatting() throws IOException{}
means that it will just throw the exception to whatever is calling the function. It can then be caught while calling that method with a try-catch block. such as
try{
whileChatting();
}
catch(IOException e){
e.printStackTrace();
}
Throwing a method basically propagates it up the chain, and so any method that calls this method will need to also include throws IOException, or the exception will need to be dealt with in the higher level method (by means of a try-catch block usually).
Catching Exceptions
Catching an exception is a way to gracefully deal with exceptions. The common thing to do is e.printStackTrace(); which prints details of the error to the console, however it's not always necessary. Sometimes you may want to do a System.exit(0) or even a System.out.println("Error in method whileCalling()")
With a catch block you can catch any type of exception! you can also do a try-catch-finally block which will run the code in the try block, catch any exceptions, and whether or not any exceptions are caught it will enter the finally block and run that code.
To know what Exception you might need to catch, you can look at the Javadocs for the class that may throw the exception. There you will find a list of every possible thing that the class can throw. You can also just catch Exception which will catch any Exception imaginable! (Well, granted it extends Exception)
And finally you can link catch blocks together like so.
try{
whileCalling();
}
catch(IOException e){
//handle this situation
}
catch(FileNotFoundException e){
//handle this situation
}
catch(Exception e){
//handle this situation
}
This will work like and else-if block and not catch duplicates.
So to answer your questions basically:
1: To throw an Exception means to have somebody else deal with it, whether this be another class, another method, or just to hoping it doesn't happen or else your program will crash(pretty bad practice).
2: To use a try catch block is to actually deal with the Exception however you see fit! printing out the stacktrace for debugging or giving the user a new prompt to re-input something maybe. (For instance a prompt that the user needs to enter a file location and then it throws a FileNotFoundException)
Hope that helps!
Two good rules of thumb:
You should only catch exceptions that you can actually handle
Throw Early/Catch Late
There's no hard and fast answer.
In general, you'll probably use "throws" much more often than you'll have a custom "try/catch". Simply because you'll have relatively few "decision" modules that "know how to recover", but you'll have correspondingly "many" modules that could throw exceptions.
You use try/catch when you want to treat its reason, otherwise you should propagate it so it can be treated at the right time.
A good start would be javadoc and tutorialspoint for exceptions
Basically is something like this:
throws - the function that throws and exception tells it's parent function that somenthing it's wrong. For instance you have a createFunction() throws SQLException where you are trying to insert 100 item in a database but the creation of number 98 fails. The createFunction() is used in your main() who receives this SQLException;
try/catch - the main() knows that createFunction() is suppose to throw an SQLException if something goes wrong so when it implements it puts it in a try/catch block, this way if an SQLException is actually thrown you can execute a fall-back plan in the catch block such as a database rollback.
Actual code of what I just said:
createFunction(Connection connection) throws SQLException {
//insert items in the database
}
main(){
try{
createFunction(connection);
}
catch (SQLException e){
connection.rollback();
}
}
The goal is to be able to do:
throw new RuntimeException();
without it printing:
Exception in thread "main" java.util.RuntimeException
at grame.GrameManager.add(GrameManager.java:40)
at grame.GrameManager.add(GrameManager.java:47)
at grame.Entity.<init>(Entity.java:56)
at grame.Entity.<init>(Entity.java:28)
at test.Test.main(Test.java:20)
(for example).
Is this possible? If so, how would I go about doing this?
Since exceptions are important, you could use a logging mechanism like log4j (http://logging.apache.org/log4j/1.2/) and set the logging to a different level when you don't want some exceptions to be printed or log to a file instead of console for example.
If you just don't care about the exception, catch it and do nothing with it (empty catch, which is awful).
You can redirect System.err by setting System.setErr(null);
No thrown exception ever directly generates a stacktrace to the error console. It's up to the code who is calling it to do so. In the case of a main program:
public static void main(String args[]) throws Exception {
// do something that throws an exception
}
If you don't catch the exception, the system will actually spit it out to the console i believe.
Somewhere along the way, you need to deal with the exception. If showing it in the GUI is what you want, then you'll have to do something like this:
public interface ExceptionHandler {
void handleException(Exception e);
}
public static void main(String args[]) {
ExceptionHandler exceptionHandler = ...;
try {
// something that might throw an exception
}
catch (Exception e) {
exceptionHandler.handle(e);
}
}
Just catch the exception, and don't put anything in the catch block.
I should add that doing this is generally a bad idea. Having that stack trace, or some sort of message is very useful when finding out what went wrong in your program.
If you want the method to kill the program without printing a stack trace, place it in a try/catch block, and under catch simply use the statement:
System.exit(1)
This lets the system know that the program exited with an irregular (non-zero) state, but does not print anything to System.err.
All that you really need to do is catch it... However, this is a really bad idea. You may want to make your own exception and catch that. This way you will not swallow exceptions that you should not be ignoring. The only time that you should really consider to do this, is if you cannot allow your application to blow up. If that is the case then you should at the very least log the error.
This explains it better than I can (and is a good resource regardless). Basically, it suggests that:
"If a client can reasonably be expected to recover from an exception,
make it a
checked exception. If a client cannot do anything to recover from the exception,
make it an unchecked exception".
Like this:
try {
some code...
} catch (RuntimeException e) {
}
1. Java compiler only cares during compilation that you have given a catch for a try, whether you implement any code in the catch or not.
2. You can keep the catch block empty, or print it on the console, log it..etc....
eg:
try{
}catch(Exception ex){
}
3. But printStackTrace() prints the method name, class name , file name and the line number where the exception has occurred.
Exception handling is the most useful mechanism to save the application from the crash. Even most of us following the exception handling mechanism. Even I see many of still getting the exceptions. Are we handling the exceptions in a way that supposed to? My question is, What is best way to handle any kind of exception?
I want to make few things clear. When I say handling an exception that does not only mean that capturing appropriate exception message and showing or logging it. Rather, it suppose to handle corrective action for exception.
Lets consider this piece of code:
try {
someMethod1();
} catch (MyException e) {
System.out.println(e.getMessage());
} catch (YourException e) {
System.out.println(e.getMessage());
}
In the above code, "MyException" and "YourException" may not catch all kind of Exception. But, of course we can use "java.lang.Exception". How would we identify the correct exception type? and how to handle that exception? especially when using external libraries.
More detail upon request.
Thanks
You do not want to capture Runtime exceptions. The reason being, you are just hiding a bug right there. Instead let the application fail and fix it. To answer to your questions, if you catch Throwable, you are going to basically eat up any kind of exceptions.
Rule of thumb: Only catch application exception.
I don't know if I'm actually getting the meaning of your question, but, you can catch as many expceptions as you need at a certain block of code:
try {
someMethod1();
} catch (MyException e) {
System.out.println(e.getMessage());
} catch (YourException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
//handle
} catch (SQLException e) {
//handle
}
And, based on exception hierarchy, when you catch a exception, you are also catching every subtype of this exception, so, when you need to catch every unexpected error condition, you can add a catch for java.lang.Exception (at the last catch statement)
try {
someMethod1();
} catch (MyException e) {
System.out.println(e.getMessage());
} catch (YourException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
//handle generic unexpected exception
}
You could also catch the super interface Throwable, but it's not recommended, as the only difference is that, aside the exceptions, you will catch the Errors too. The errors are fatal conditions, which should not be handled, as they use to mean serious problems at the java VM, as Out of Memory, Stack Overflow, etc.
These links can be useful on how to handle java Exceptions:
http://download.oracle.com/javase/tutorial/essential/exceptions/index.html
http://tutorials.jenkov.com/java-exception-handling/index.html
Regards.
Guys from Software Engineering Radio podcast had two very good episodes on Error Handling.
If you really want to catch every possible exception, catching Throwable is what you want to do:
try {
somethingThatMayFail();
} catch (Throwable t) {
t.printStackTrace();
}
More often than not, this is a bad idea, though. You shouldn't catch any exceptions if you don't know why they occurred, or how to clean up after them. Not crashing is not necessarily a good thing - if your program is broken, crashing is the responsible thing to do. Consider this method:
public Thing loadThing(long id){
try {
return doLoad(id);
} catch (Throwable t) {
// What do we do here?
}
}
The compiler forces you to return or throw something from every possible execution path of the method, but only the non-exceptional path allows us to return something sensible. We could return null from the catch clause, but then the calling code might forget checking the return value for null, which means you'll instead end up with a NullPointerException which is far harder to decipher since it doesn't tell you what the real error was or where it occurred.
Exceptions are good. There are reasons why every sensible language has them.
The type of any object can be inspected via reflection. But i don't like using it much.
try {
throw new Exception1();
} catch (Throwable t) {
// just get name
System.out.println(t.getClass().getName() + " caught");
// or try instanceof - this is not nice approach IMO
if (t instanceof Exception1) {
System.out.println("yes exception1");
}
}
BTW did think or heard about AOP? To be more precise about AspectJ. Aspect oriented programming can be answer to your question how to print or log exceptions while your code is still clean and easily maintainable. If you are using Java EE and EJB, you can try interceptors mechanism instead of AspectJ. I recommend you read something about AOP and AspectJ (for Java).
cheers
It sounds like you're trying to figure out how to know when you've handled every possible exception. If you just don't put a throws clause on your method then the compiler will tell you which exceptions you need to put handlers for.
If you are using Eclipse, one way is to write the code with out exception handling and it will make you see the types of exceptions that your code might throw.
If you want your program sequence to continue as you have coded, then you can surround only that part of code that might throw an exception and in the Catch block perform necessary steps so that your program works in the flow you want.
something like
"
code ...
try{
something....
}catch(someException e){
// handle it
}
try{
something....
}catch(someException e){
// handle it
}
code ...
"
However this code does not catch any exception that may occur otherwise (i.e, not because of your code). For that an Outer Try Catch might help you find out that it was something else
like
"
try
{
code ...
try{
something....
}catch(someException e){
// handle it
}
try{
something....
}catch(someException e){
// handle it
}
code ...
}
catch(runtime e){
//tell user/log that something unexpected has occured
}
"
Your code is correct. If someMethod1() method does not declare any other Exceptions, they are RuntimeExceptions and you are supposed to catch RuntimeException.