How to effectively handle any kind of exceptions?

这一生的挚爱 提交于 2019-12-11 12:54:49

问题


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


回答1:


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.




回答2:


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.




回答3:


Guys from Software Engineering Radio podcast had two very good episodes on Error Handling.




回答4:


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.




回答5:


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




回答6:


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.




回答7:


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 } "




回答8:


Your code is correct. If someMethod1() method does not declare any other Exceptions, they are RuntimeExceptions and you are supposed to catch RuntimeException.



来源:https://stackoverflow.com/questions/4406849/how-to-effectively-handle-any-kind-of-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!