Java Try-Catch Questions

Status
Not open for further replies.

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
I’m trying to grasp try-catch-finally in Java. I have two questions. These questions might sound silly, please bear in mind that I’m still a beginner.
1) Is it possible/recommended to just wrap a whole method in a try{}block?
See these samples:
Code:
Public void myMethod(){
     try{
          //200 lines of code
          //5 lines of code that might throw an exception
          //200 more lines of code
     }
     catch(someException e){
          //do stuff to handle the exception.
     }
}
Code:
Public void myMethod(){
     //200 lines of code
     Try{ 
          //5 lines of code that might throw an exception
     }
     Catch(someException e){
          //do stuff to handle the exception.
     }
     //200 more lines of code
}
The second sample looks cleaner to me. It specifies exactly which lines could throw an exception. But if there functionally any difference between the two? Will the two samples behave differently?


2) Is it possible to make classes and methods for handling exceptions? Say your program has 20 sections that might all throw IOException. Of course, you condense those lines into reusable classes as much as possible, but you still have 20 distinct spots where IOExceptions can be thrown. For whatever reason, the code inside your catch{} blocks is 200 lines long. You could write those 200 lines 20 times over. Instead could you create an ExceptionHandler.java class and put your 200 lines of code in static methods there? Something like:
Code:
Catch(IOException e){ExceptionHandler.ioHandler(e);}
Catch(FileNotFoundException e){ExceptionHandler.fnfHandler(e);}
That seems possible, and it seems like it would be much cleaner.
 

CthulhuDragon

Ars Tribunus Angusticlavius
6,157
Basically, it depends. If there is nothing you can do to recover from any exception, it may make sense to wrap everything that can throw an exception, catch it, log it and return or throw.

If however the exception is something you can handle, you should wrap the smallest part possible, handle that error and let your program continue on.
 

wallinbl

Ars Legatus Legionis
14,319
Subscriptor
400 lines of code seems excessive for a method. Simplifying all that might help with more clarity on where to handle the exceptions.

The answer to your question really depends on how the exception impacts the remainder of the processing, whether it needs to alert the user in some way, etc. Are you rolling back and reverting if it happens? Are you moving on and noting that it happened?

Also, you might be surprised at where exceptions crop up - it's hard to imagine that two blocks of 200 lines don't need any exception handling.
 
But the stack trace tells you the line where the exception occurred. You aren't silently suppressing the exception, right?

As for item 2 of the OP, sure you can factor functionality out of the catch block. Why would you think otherwise? Having multiple occurrences of a 200 line code block in catch clauses sets off a red flag, but regardless, it's better to factor out that code than to duplicate it.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
incidentally, aside from what sounds like horrifically long methods this is precised what things like first class functions/meta programming were designed to solve.

Say you are writing an app where a bunch of IOOperations will be queued up to excute, and you are happy to allow each to individually fail and be logged without affecting the others[1]

in c#:

Code:
public SuccessOrFailure TryIOOperation(Action operation)
{
    try
    {
        operation();
        return SuccessOrFailure.Success;
    }
    catch (IOException e)
    {
        // log it, put it in the SuccessOrFailure value etc.
        // just don't totally swallow it
        return SuccessOrFailure.Failure(e);
    }
}

In older java world you would wrap each operation into some "IOOperation" class/interface or use Runnable.

There are more potent meta programming techniques, though I find first class functions very easy to debug through with appropriate compiler/debugger smarts I haven't actually tried Lisp in this regard so it might rock.

I will second all that has been said about having 200 lines inside a catch block. Something is *very* wrong if you're doing that.

1. a more likely thing is that the operations in fact form a directed acyclic forest but this example is simpler
 

OmniWrench

Ars Scholae Palatinae
1,427
[url=http:/civis/viewtopic.php?p=25121745#p25121745:1fqwtxpk said:
Solomonoff's Secret[/url]":1fqwtxpk]But the stack trace tells you the line where the exception occurred. You aren't silently suppressing the exception, right?

Hmmm, it was a number of years ago but I specifically remember having issues where we weren't able to determine which of a set of lines in the same "catch" block were throwing a hard-to-reproduce exception. I'm no longer at that company any more (and not doing Java anymore) so I'm fuzzy on why we may have ended up in that situation...
 
D

Deleted member 43669

Guest
Most of the time you want to use throws, or if you're fancy, big try with catch that (optionally) logs and wraps and rethrows.

You rarely handle exceptions- most of the time you catch them in a very top-level piece of code that displays an error message and not much else. If you find yourself writing significant code in catch blocks, you're probably doing control flow with exceptions and you should avoid it.

Dealing with unreliable third parties is properly handled with higher level structures as per Shuggy's post.
 

w00key

Ars Legatus Legionis
10,099
Subscriptor
[url=http:/civis/viewtopic.php?p=25122705#p25122705:2b3cwt30 said:
ShuggyCoUk[/url]":2b3cwt30]
so I'm fuzzy on why we may have ended up in that situation...

Running release mode code.

In optimized code you often cannot easily map back precisely to a line number. In .Net you can provide the pdb files with Release builds but you have to accept that sometimes the line number is... a heuristic.

Java's release mode still contains all debug information unless you strip it explicitly. But exception traces/causes do get lost because libraries don't always chain them properly, some parts of Android is silly like that.


Real world example: https://bugzilla.mozilla.org/show_bug.cgi?id=847021

Source: https://android.googlesource.com/platfo ... elper.java

At 190, exception is logged with error severity, silently ignored. This looks innocent, until
At 199, system discovers that the previously ignore exception is critical, rethrows a new one without the original stack trace and message/cause.

--

@ unchecked vs checked exceptions, it's a holy war with good arguments on both sides. I kinda like how IOExceptions are declared so you don't forget about them, not handling them properly usually means a failed action (caught -> noop) without crashing the program. On the other side, 99.9% of Android's own libraries (SQLite) are unchecked, not handling the SQLiteException often means crashing with a force close when something unexpected happens. It's less verbose tho, I don't really mind that.

Both variants work fine, but on the unchecked side, I've seen function calls throwing SQLiteException in one version (Android 2.3.x), and IllegalArgumentException in another (anything else?). With declared exceptions in the signature this cannot happen.
 
Status
Not open for further replies.