开发者

Exception handling protocol for methods

开发者 https://www.devze.com 2023-01-02 04:10 出处:网络
Is there any specific protocol for handling exceptions in public methods? Consider this eg. public int someMethod()

Is there any specific protocol for handling exceptions in public methods? Consider this eg.

public int someMethod()
{
  try{
  code that might throw an exception    
  }
  catch(Exception e)
  {
     log the exception
  }
}

Say that this method might throw an ArrayIndexOutOfBoundsException. So, is it correct to handle this Exception in the method itself (as in the example) or throw it and assume that the calling method will handle the Exception?

Edit: Further extending my ques开发者_高级运维tion. Consider the following function.

public int[] someMethod2()
{
  try{
code that might throw an exception    
 }
catch(Exception e) {
  log the exception
  return new int[0];
 }
}

As in the example code above, if I return an array of size 0, then the calling method will fail with an AraryIndexOutOfBounds Exception. If I return null, then the calling method will fail with NullPointer Exception. Since, I can modify the calling method, which way is better? Should I let the calling method fail? Or should I directly call System.exit() in someMethod2()?

Is there a tutorial which explains these decisions? This does not give me an answer.


Generally, don't handle the exception if it doesn't make sense to handle it yourself. ArrayIndexOutOfBoundsException usually is a sign of a programming error, and if your app contains programming errors, crashing is the correct and responsible thing to do.

One big no-no is returning null instead of throwing exceptions, like this code:

public Thing getThingById(long id) {
    try {
        ResultSet rs = queryDatabase("SELECT * FROM THING WHERE ID = " + id);
        rs.next();
        return new Thing(rs.get(1), rs.get(2), rs.get(3));
    } catch (Exception e) {
        return null;
    }
}

Now, if you get null from this method, you don't know why. Was the ID invalid? Is the database server down? Or was it some programming error in the queryDatabase method?

Edit: Oh, and you should never log and rethrow, it'll just fill up your logs and make them unreadable. If you rethrow an exception, odds are that whatever code catches it further up the call chain will log it, too


Neither. Do nothing. ArrayIndexOutOfBoundsException indicates a programming error, which should either not be caught at all, or only be caught at a high level of the app. Since it'S a subclass of RuntimeException, you don't have to declare that the method throws it either.

This is the whole point of exceptions: you can choose where in the call stack to catch them, and in most cases, you should not catch them right where they might be thrown.


it depends on if you can catch the exception in a meaningful way, or on the code contract this method is working with, e.g. what does the caller of the method expect, etc


This is entirely for you to decide. If the purpose of the method is safe access to an array, you should handle it in that method. But if you are doing something totally different, you should rethrow. Good way to think about error handling is to handle the error where it is appropriate.


I usually handle everything that is possible as locally as possible and the vast majority of exceptions are both expected and recoverable in my experience. Sometimes locally does not have to mean the same method and there is nothing to feel ashamed of of throwing an exception out of a method where it cannot be handled.

Additionally, I usually identify a level in the program where I want to handle the exceptions that I could not handle elsewhere. This may be the top level, or somewhere in the middle of the current stack where a partial recovery can be made.

Usually this handling simply involves logging the non-expected exception and closing down the application gracefully (in the case of non-interactive applications) or terminating the current thread of execution in more interactive applications.

The way of handling this exception is heavily application-specific but you should always start with a catch-all at your top level that will log Exceptions and Errors no matter what then write additional handlers at areas in your application where Exceptions may be recoverable.

You should never try to recover from an Error however but you may still wish to catch them (seperately) for purposes of graceful shutdown (although this is not guarenteed in the case of Errors).

0

精彩评论

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