Java vs Objective-C : Exception, reaching of finally block - java

I test exceptions using in java an dobjective-C programs.
In these tests, I see a difference in the way of finally block is reached when an exception is catched and rethrown.
Here my java test :
try {
Boolean bThrow = true;
System.out.println("try : before exception sent");
if (bThrow) {
throw new Exception();
}
System.out.println("try : after sent");
}
catch (Exception e) {
System.out.println("catch, rethrow");
throw e;
}
finally {
System.out.println("finally");
}
which displays :
try: before exception sent
catch, rethrow
finally
And here my objective-c test :
#try {
NSException *myexc = [NSException exceptionWithName:#"exceptionTest" reason:#"exceptionTest" userInfo:nil];
BOOL bThrow = YES;
NSLog(#"try : before exception sent");
if (bThrow) {
#throw myexc;
}
NSLog(#"try : after sent");
}
#catch (Exception *exception) {
NSLog(#"catch, rethrow");
#throw exception;
}
#finally {
NSLog(#"finally");
}
which displays :
try: before exception sent
catch, rethrown
*** Terminating app
Code in finally block is not reached !
Why this difference ?
[EDIT] Sorry, #try ... #try ... #try... was a mistake.
I changed it, but the problem is the same, i can't reach finally block in objective-c test

Your Objective-C code does not have a finally block, just three try blocks. It should look like this:
#try {
NSException *myexc = [NSException exceptionWithName:#"exceptionTest" reason:#"exceptionTest" userInfo:nil];
BOOL bThrow = YES; // Use BOOL or bool
NSLog(#"try : before exception sent");
if (bThrow) {
#throw myexc;
}
NSLog(#"try : after sent");
}
#catch (NSException *e) { // use catch not another try
NSLog(#"catch, rethrow");
#throw e;
}
#finally { // use finally not another try
NSLog(#"finally");
}

OK, i solved my problem.
In my objective-c test, application crashed, that's why finally block was not reached.
If I add a try catch block in the main, now in my function, finally block is reached !
So, I confirm that finally block is still reached whatever an excpetion occurs (and is rethrown) or not).

Related

How to avoid throw clause in finally block

I am using SonarQube for code quality. I got one issue related to exception handling, which says remove throw clause from finally block.
} catch(Exception e) {
throw new MyException("request failed : ", e);
} finally {
try {
httpClient.close();
} catch (IOException e) {
throw new MyException("failed to close server conn: ", e);
}
}
Based on my understanding above code looks good. If I remove throw clause and suppress exception in finally then caller of this method will not be able to know server's status. I am not sure how we can achieve same functionality without having throw clause.
Your best shot is to use the Automatic Resource Management feature of Java, available since Java 7. If that is for some reason not available to you, then the next best thing is to replicate what that syntactic sugar expands into:
public static void runWithoutMasking() throws MyException {
AutoClose autoClose = new AutoClose();
MyException myException = null;
try {
autoClose.work();
} catch (MyException e) {
myException = e;
throw e;
} finally {
if (myException != null) {
try {
autoClose.close();
} catch (Throwable t) {
myException.addSuppressed(t);
}
} else {
autoClose.close();
}
}
}
Things to note:
your code swallows the original exception from the try block in case closing the resource fails. The original exception is surely more important for diagnostic;
in the ARM idiom above, closing the resource is done differently depending on whether there already was an exception in the try-block. If try completed normally, then the resource is closed outside any try-catch block, naturally propagating any exception.
Generally, methods in the finally block are 'cleanup' codes (Closing the Connection, etc) which the user does not necessarily need to know.
What I do for these exceptions is to absorb the exception, but log the details.
finally{
try{
connection.close();
}catch(SQLException e){
// do nothing and just log the error
LOG.error("Something happened while closing connection. Cause: " + e.getMessage());
}
}
You're getting a warning because this code could potentially throw an exception while dealing with a thrown exception. You can use the try with resource syntax to close the resource automatically. Read more here.
In the case that the "request failed : " exception is thrown and you fail to close the httpclient, the second exception is the one that would bubble up.
I am not sure how we can achieve same functionality without having
throw clause.
You could nest the two try blocks differently to achieve the same result:
HttpClient httpClient = null; // initialize
try {
try {
// do something with httpClient
} catch(Exception e) {
throw new MyException("request failed : ", e);
} finally {
httpClient.close();
}
} catch (IOException e) {
throw new MyException("failed to close server conn: ", e);
}

JAVA - continue after file not found exception

I have the following function that read data from file.
If i get an IO exception, I want to finish the run of this function and continue to next functions in this program.
what should i add to the code?
I tried to add continue to the finnally block but I get error "continue cannot be used outside of a loop".
public void readFromFile() throws Exception
{
BufferedReader f= new BufferedReader(new FileReader("C:\\T.DAT"));
String l="";
try{
do{
l = f.readLine();
if(l != null)
{
Car a = new Car();
a.setFromLine(l);
alCars.add(a);
}
} while(line !=null);
}
catch (Exception e)
{
System.out.println("can't open file IO ERROR. program is continueing");
}
finally
{
f.close();
}
}
simply put return; in the finally block
You cannot use continue outside the loop.
Catch and finally is outside the loop.
Insert try - catch - finally into the do while clause and it would work.
If you use catch block you don't have to use throws after method signature.
Simply catch Exception in catch block, and in finally do something.
Do first catch for IOException and in all other cases do another catch for Exception.
try {
//
}
catch ( IOException e ) {
System.out.println("IO Exception occured");
}
catch ( Exception e ) {
//other exceptions
}
finally {
//deinitialize
}
I am not sure if ioexception occurs, then in finally you have to close file. maybe it's null object
You don't have to do anything. The code will return from the function after the finally block has been executed.

Java: Exception Handler

I have a project having Exception handling written in the following way:
Parent class has all the exception handling logic. And the invoked class just throws exception and the invoker class handles with appropriate logic.
Now the problem that I am facing invoked class opens different stuffs for example, a file. These files are not getting closed at the time of exception.
so what should be the appropriate way of exception handling in this case.
class A
{
private void createAdminClient()
{
try
{
B b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1)
{
}
catch(CustomException2 e1)
{
}
catch(CustomException3 e1)
{
}
catch(CustomException4 e1)
{
}
}
}
class B
{
................
................
getClinetHandler() throws Exception
{
--------------------------
---- open a file----------
--------------------------
----lines of code---------
--------------------------
Exceptions can happen in these lines of code.
And closing file may not be called
--------------------------
---- close those files----
--------------------------
}
}
You can wrap the code which may throw an exception in a try...finally block:
getClientHandler() throws Exception {
// Declare things which need to be closed here, setting them to null
try {
// Open things and do stuff which may throw exception
} finally {
// If the closable things aren't null close them
}
}
This way the exception still bubbles up to the exception handler but the finally block ensures that the closing code still gets called in the event of an exception.
use a finally block to complete the final tasks. for example
try
{
B b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1)
{
}
finally{
// close files
}
From the doc
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
This is how I do it
try {
//What to try
} catch (Exception e){
//Catch it
} finally {
//Do finally after you catch exception
try {
writer.close(); //<--Close file
} catch (Exception EX3) {}
}
Use a finally block to handle post-processing execution (regardless whether it succeeded or failed). Like so:
// Note: as Sean pointed out, the b variable is not visible to the finally if it
// is declared within the try block, therefore it will be set up before we enter
// the block.
B b = null;
try {
b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1) {
} // and other catch blocks as necessary...
finally{
if(b != null)
b.closeFiles() // close files here
}
The finally block is always executed, regardless, even if you throw or return from the try or catch blocks.
This answer provides a very good explanation of how the finally block works in this situation, and when/how it is executed, and basically further illustrates what I just wrote.

While loop inside try block

I am trying to put a while loop inside a try /catch block. To my curiosity finally of that try catch is not executed when the while loop exits. Can some explain what is happening actually?
I tried to google, but cnould not find any details.
I assume your code looks like this:
try
{
while (...)
{
// ...
}
}
catch (FooException ex)
{
// This only executes if a FooException is thrown.
}
finally
{
// This executes whether or not there is an exception.
}
The catch block is only executed if there is an exception. The finally block usually executes whether or not an exception was thrown. So you will probably find that your finally block is actually being executed. You can prove this to yourself by placing a line there that causes some output to the console.
However there are situations in which the finally block doesn't run. See here for more details:
Does a finally block always run?
It can happen only if your program exits either by using System.exit() or if an Error or Throwable were thrown (vs. Exception that will be caught).
Try the following:
public static void main(String[] args) {
try{
System.out.println("START!");
int i=0;
while(true){
i++;
if(i > 10){
System.exit(1);
}
}
}
catch (Exception e) {
// TODO: handle exception
}
finally{
System.out.println("this will not be printed!");
}
}

throws Exception in finally blocks

Is there an elegant way to handle exceptions that are thrown in finally block?
For example:
try {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}
finally {
try{
resource.close();
}
catch( Exception ex ) {
// Could not close the resource?
}
}
How do you avoid the try/catch in the finally block?
I usually do it like this:
try {
// Use the resource.
} catch( Exception ex ) {
// Problem with the resource.
} finally {
// Put away the resource.
closeQuietly( resource );
}
Elsewhere:
protected void closeQuietly( Resource resource ) {
try {
if (resource != null) {
resource.close();
}
} catch( Exception ex ) {
log( "Exception during Resource.close()", ex );
}
}
I typically use one of the closeQuietly methods in org.apache.commons.io.IOUtils:
public static void closeQuietly(OutputStream output) {
try {
if (output != null) {
output.close();
}
} catch (IOException ioe) {
// ignore
}
}
If you're using Java 7, and resource implements AutoClosable, you can do this (using InputStream as an example):
try (InputStream resource = getInputStream()) {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}
Arguably a bit over the top, but maybe useful if you're letting exceptions bubble up and you can't log anything from within your method (e.g. because it's a library and you'd rather let the calling code handle exceptions and logging):
Resource resource = null;
boolean isSuccess = false;
try {
resource = Resource.create();
resource.use();
// Following line will only run if nothing above threw an exception.
isSuccess = true;
} finally {
if (resource != null) {
if (isSuccess) {
// let close throw the exception so it isn't swallowed.
resource.close();
} else {
try {
resource.close();
} catch (ResourceException ignore) {
// Just swallow this one because you don't want it
// to replace the one that came first (thrown above).
}
}
}
}
UPDATE: I looked into this a bit more and found a great blog post from someone who has clearly thought about this more than me: http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html He goes one step further and combines the two exceptions into one, which I could see being useful in some cases.
As of Java 7 you no longer need to explicitly close resources in a finally block instead you can use try-with-resources syntax. The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Assume the following code:
try( Connection con = null;
Statement stmt = con.createStatement();
Result rs= stmt.executeQuery(QUERY);)
{
count = rs.getInt(1);
}
If any exception happens the close method will be called on each of these three resources in opposite order in which they were created. It means the close method would be called first for ResultSetm then the Statement and at the end for the Connection object.
It's also important to know that any exceptions that occur when the close methods is automatically called are suppressed. These suppressed exceptions can be retrieved by getsuppressed() method defined in the Throwable class.
Source: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Ignoring exceptions which occur in a 'finally' block is generally a bad idea unless one knows what those exceptions will be and what conditions they will represent. In the normal try/finally usage pattern, the try block places things into a state the outside code won't be expecting, and the finally block restores those things' state to what the outside code expects. Outside code which catches an exception will generally expect that, despite the exception, everything has been restored to a normal state. For example, suppose some code starts a transaction and then tries to add two records; the "finally" block performs a "rollback if not committed" operation. A caller might be prepared for an exception to occur during the execution of the second "add" operation, and may expect that if it catches such an exception, the database will be in the state it was before either operation was attempted. If, however, a second exception occurs during the rollback, bad things could happen if the caller makes any assumptions about the database state. The rollback failure represents a major crisis--one which should not be caught by code expecting a mere "Failed to add record" exception.
My personal inclination would be to have a finally method catch exceptions that occur and wrap them in a "CleanupFailedException", recognizing that such failure represents a major problem and such an exception should not be caught lightly.
One solution, if the two Exceptions are two different classes
try {
...
}
catch(package1.Exception err)
{
...
}
catch(package2.Exception err)
{
...
}
finally
{
}
But sometimes you cannot avoid this second try-catch. e.g. for closing a stream
InputStream in=null;
try
{
in= new FileInputStream("File.txt");
(..)// do something that might throw an exception during the analysis of the file, e.g. a SQL error
}
catch(SQLException err)
{
//handle exception
}
finally
{
//at the end, we close the file
if(in!=null) try { in.close();} catch(IOException err) { /* ignore */ }
}
Why do you want to avoid the additional block? Since the finally block contains "normal" operations which may throw an exception AND you want the finally block to run completely you HAVE to catch exceptions.
If you don't expect the finally block to throw an exception and you don't know how to handle the exception anyway (you would just dump stack trace) let the exception bubble up the call stack (remove the try-catch from the finally block).
If you want to reduce typing you could implement a "global" outer try-catch block, which will catch all exceptions thrown in finally blocks:
try {
try {
...
} catch (Exception ex) {
...
} finally {
...
}
try {
...
} catch (Exception ex) {
...
} finally {
...
}
try {
...
} catch (Exception ex) {
...
} finally {
...
}
} catch (Exception ex) {
...
}
After lots of consideration, I find the following code best:
MyResource resource = null;
try {
resource = new MyResource();
resource.doSomethingFancy();
resource.close();
resource = null;
} finally {
closeQuietly(resource)
}
void closeQuietly(MyResource a) {
if (a!=null)
try {
a.close();
} catch (Exception e) {
//ignore
}
}
That code guarantees following:
The resource is freed when the code finished
Exceptions thrown when closing the resource are not consumed without processing them.
The code does not try to close the resource twice, no unnecessary exception will be created.
If you can you should test to avoid the error condition to begin with.
try{...}
catch(NullArgumentException nae){...}
finally
{
//or if resource had some useful function that tells you its open use that
if (resource != null)
{
resource.Close();
resource = null;//just to be explicit about it was closed
}
}
Also you should probably only be catching exceptions that you can recover from, if you can't recover then let it propagate to the top level of your program. If you can't test for an error condition that you will have to surround your code with a try catch block like you already have done (although I would recommend still catching specific, expected errors).
You could refactor this into another method ...
public void RealDoSuff()
{
try
{ DoStuff(); }
catch
{ // resource.close failed or something really weird is going on
// like an OutOfMemoryException
}
}
private void DoStuff()
{
try
{}
catch
{
}
finally
{
if (resource != null)
{
resource.close();
}
}
}
I usually do this:
MyResource r = null;
try {
// use resource
} finally {
if( r != null ) try {
r.close();
} catch( ThatSpecificExceptionOnClose teoc ){}
}
Rationale: If I'm done with the resource and the only problem I have is closing it, there is not much I can do about it. It doesn't make sense either to kill the whole thread if I'm done with the resource anyway.
This is one of the cases when at least for me, it is safe to ignore that checked exception.
To this day I haven't had any problem using this idiom.
try {
final Resource resource = acquire();
try {
use(resource);
} finally {
resource.release();
}
} catch (ResourceException exx) {
... sensible code ...
}
Job done. No null tests. Single catch, include acquire and release exceptions. Of course you can use the Execute Around idiom and only have to write it once for each resource type.
Changing Resource from best answer to Closeable
Streams implements Closeable Thus you can reuse the method for all streams
protected void closeQuietly(Closeable resource) {
if (resource == null)
return;
try {
resource.close();
} catch (IOException e) {
//log the exception
}
}
I encountered a situation similar where I couldn't use try with resources but I also wanted to handle the exception coming from the close, not just log and ignore it like closeQuietly mechanism do. in my case I'm not actually dealing with an output stream, so the failure on close is of more interest than a simple stream.
IOException ioException = null;
try {
outputStream.write("Something");
outputStream.flush();
} catch (IOException e) {
throw new ExportException("Unable to write to response stream", e);
}
finally {
try {
outputStream.close();
} catch (IOException e) {
ioException = e;
}
}
if (ioException != null) {
throw new ExportException("Unable to close outputstream", ioException);
}

Categories