-1

I have learnt basic of java. I wanted to know about exception handling.

1) Is it OK to use

try{............
}catch(Exception ex){
........
}

instead of something more specific like

try{............
}catch(FileNotFoundException ex){
........
}

This way i do not know what type of exception will be thrown.

2) How to decide what part of code be inside try block. Will it be bad if I put whole code inside `try' and turn my face.

3) If I have to be be specific about catch block, then how do I know what type of exception can be thrown ?

John Watson
  • 869
  • 3
  • 16
  • 32
  • 2
    No, that's generally not OK, because you're mainly hiding bugs. – Denys Séguret Jun 16 '12 at 14:09
  • I also read all answers below; but about 2nd question what i think is that if all of a method block needs to be inside a try/catch, then you should make the method throw the (checked) exception and catch it in the caller. – guido Jun 16 '12 at 14:19
  • possible duplicate of [Is it good to catch a more general type of Exception?](http://stackoverflow.com/questions/894710/is-it-good-to-catch-a-more-general-type-of-exception) – Denys Séguret Jun 16 '12 at 14:49

5 Answers5

1

That's a bad variant. An example:

socket.send(data); // sending data via socket. This may cause IOException

But there can be another Exception, for example NullPointerException. If you will catch all exceptions it will be harder to find mistake:

Socket socket = null;
socket.send(data); // sending data via socket. This will cause NullPointerException

In this example you see that you will have a NullPointerException but you will thinking this is an IOException

The best variant is:

try {
    Socket socket = null;
    socket.send(data);
} catch(IOException ex) {
    ex.printStackTrace();
} catch(NullPointerException ex) {
    ex.printStackTrace();
}
// or in java 7 you can write catch(IOException | NullPointerException ex)

if you want to catch a few exceptions, or don't write second catch block if there must not be null, you will find all your mistakes and this will be needn't.

Sorry for my English

alaster
  • 3,821
  • 3
  • 24
  • 32
  • how will one know what all exceptions will be thrown by the code ? – John Watson Jun 16 '12 at 14:23
  • There are exceptions that you don't need to catch. All unhandled exceptions are catched, so you will see an errors in your code. You need to catch only exceptions you want to handle. In my example you can reconnect socket if you get an exception. All methods provides information about what exceptions they can throw. See javaDoc for methods you are using – alaster Jun 16 '12 at 14:27
1
  1. instead of something more specific is better option if you can
  2. if you put whole code inside `try' you can't be specific for exception and even your handling (what should be done of exception) will be limited

as I told instead of something more specific is better option if you can but if you are not sure then can use this way

try{............
}catch(FileNotFoundException ex){
........
}catch(Exception ex){
........
}

means general exaction should come in last.

Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
0

Java have two types of Exception

1 Checked Exception

2 Unchecked Exception

So your question is How to decide what part of code be inside try block.

Java enforce you write block of code inside try block which possibly may cause first type of exception.

you can write e.printStackTrace(); to know details about what caused the exception.

Vipul
  • 27,808
  • 7
  • 60
  • 75
0

And the answer is.... It depends.

If you want your application to behave differently for different exception types, then your try blocks should be short, and you should catch exceptions separately.

If, however, you decide that your code failure should be handled in an universal way, you may catch all exceptions in one catch block, and, for example do something like this:

try {

    // large block of code, throwing lots of exceptions

} catch (Throwable t) {

    // This way you, and your admin will know what really happened.
    logger.log(Level.SEVERE, "Error in my awesome block of code", t);


    // This way you're hiding error details from your users
    someGUI.showErrorMessage("Unexpected error during processing. Contact your local IT");
}

In real life this is usually more complicated than this, and you should decide which errors to handle separately, and which in a single, universal way.

npe
  • 15,395
  • 1
  • 56
  • 55
  • As I know it's a bad idea to catch `Throwables` instead of `Exceptions`. An [Error](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Error.html) is a `Throwable` but it must not be catched. – alaster Jun 16 '12 at 14:18
  • There are some cases when you _should_ catch `Errors`. Like when dynamically loading classes (`NoClassDefFoundError`). Or when you are _expecting_ OOMEs, but don't want your application to break, ans so on. – npe Jun 16 '12 at 14:20
  • how do you recover from a NoClassDefFoundError? – guido Jun 16 '12 at 14:25
  • You display a message, that there's something very wrong with the plugin or a library that the user is trying to load. – npe Jun 16 '12 at 14:38
  • If you do so you must trow it again inside your `catch` block: `throw t;` – alaster Jun 16 '12 at 14:44
  • Example: if you deploy Web-App onto JBoss without dependencies, deployment will fail with `NoClassDefFoundError`. JBoss catches this Error, logs it, and rethrows DeploymentException (not the Error itself), which is catched later. Throwing an error to the top would probably stop the whole JBoss because of a single bad deployment. So, no - you don't **have to** rethrow it. You **may**, rethrow it if you cannot handle it or recover from it. – npe Jun 16 '12 at 14:48
-1

1) Using try{..}catch(Exception e) {..} makes your code more compact and able to manage the exception in a single place. You can also concatenate the catch blocks in order to manage several type of exceptions:

try {
    ..
} catch(FileNotFoundException fe) {
    //manage here this kind of exception
} catch(NullPointerException ne) {
    //you missed a check on nulls! But the file has been found...
} catch(Exception e) {
    //file has been found and no nulls are left...
}

Note that the order of blocks is relevant: in the example, if there's both a FileNotFoundException and a NullPointerException, you will be redirected in the FileNotFoundException catch block.

2) try-catch block obviously have an impact on performances of your code, so I think you need to place only the code that: - is not under your control (e.g. third-party libraries, etc.) - uses un-reliable media (e.g. socket connections, file IO, etc.) - take advantage of exception handling to signal specific behavior (e.g. GoogleAppEngine timeout exceptions, etc.)

Cristiano Ghersi
  • 1,944
  • 1
  • 20
  • 46
  • 1
    i dont get your note about catch ordering; if both a npex and a fnfex are in a try block, you are actually directed to whichever happens first (and wont see the second) – guido Jun 16 '12 at 14:23
  • could you please explain what will be the impact on the performance – John Watson Jun 16 '12 at 14:26
  • @guido: if you think npex is more important than fnfex, you need to swap the two catch blocks... – Cristiano Ghersi Jun 17 '12 at 19:49
  • 1
    @JohnWatson: under the covers, compiled code needs to check every instruction if there's been an exception or not. It depends how the JVM is implemented, but usually it slows down by an order of magnitude, more or less – Cristiano Ghersi Jun 17 '12 at 19:52
  • @Cristiano Ghersi nope, catch order has nothing to do with exception importance, but with exception hierarchy. When an exception occurs, each handler is checked in order and the handler that first matches is executed. This means you should order the catches in bottom-top order along hierarchy (ie not swallowing a IOException as a plain Exception). – guido Jun 18 '12 at 04:52
  • @CristianoGhersi does that mean, I should put bare minimum code within `try` block to reduce overhead. do i need to catch all exceptions ? how to decide which one to catch ? – John Watson Jun 18 '12 at 06:20
  • 1
    @JohnWatson: yes, I think you should put the minimum code inside try-catch block. Usually I catch only the exceptions in the "throws" list of invoked methods. For the other ones (e.g. NullPointerException) you should be able to check them with simple "if" in the code – Cristiano Ghersi Jun 19 '12 at 07:36