开发者

Simple question about try/catch statement

开发者 https://www.devze.com 2023-02-22 20:21 出处:网络
If I add this try/catch statement in my code: try { ... method1(); } catch (Exception e) { 开发者_如何学Python call_method();

If I add this try/catch statement in my code:

try {
   ...
   method1();

} catch (Exception e) {
  开发者_如何学Python call_method();

}

am I invoking "call_method()" for any type of exception, at any level such as java.lang.NullPointerException inside method1() .. right ?

thanks


am I invoking "call_method()" for any type of exception, at any level such as java.lang.NullPointerException inside method1() .. right ?

Yes........


Yes, that will catch anything that extends Exception. Note especially that this include RuntimeException and its many subclasses (such as NullPointerException as you mention).

It will not catch other Throwable objects, i.e. Error and its many subclasses.

You should be careful not to write overly-broad exception handlers that will end up concealing important problems. (Whether that's the case in this example, I can't say.)


That would be a steady: Yes! :-D


Yes, that's correct. However, the catch block will not trigger for Errors, such as an OutOfMemoryError. Which is generally what you want since Errors are supposed to signal fundamental problems an app cannot recover from.


Since you are catching the generic Exception, you will be calling call_method() every time an exception is thrown.

You can see here:

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Exception.html

That exception is the top level class for the exceptions, in which everything eventually inherits from.

However as a rule of thumb, you generally do not want to catch Exception, rather you want to catch specific errors that are pertaining to your try, catch block.


Yes - for anything that inherits from Exception. Although in general, unless that method is doing something to handle that exception, it's not typically considered "good form" (but I don't try to assume a person's intent).

You may want to look at Throwable as well: here is a good discussion to view: When should Throwable be used instead of new Exception?


For any exception thrown inside the try block, you will be calling the call_method().

It is because you are trying to catch generic Exception object and not some specific object such as NullPointerException.

If you try something like this,

try { 
  // ....
  method1();
 }
catch(NullPointerException e) {
  // ....
  call_method();
 }  

then only when you have a NullPointerException inside the try block, your catch will catch it & your call_method() will be executed.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号