When to use exceptions in Java (example)

前端 未结 10 1745
既然无缘
既然无缘 2020-12-06 17:05

I know that this would be bad practice although I know that I would not be able to explain why.

int [] intArr = ...
...
try{
   int i = 0;
   while(true){
         


        
相关标签:
10条回答
  • 2020-12-06 17:35

    You are correct. Exceptions should not be used to handle process flow.

    0 讨论(0)
  • 2020-12-06 17:36

    Exceptions should catch something exceptional, log it, and recover if possible.

    If it's part of normal program flow, you should handle it normally.

    0 讨论(0)
  • 2020-12-06 17:37

    You are right: exceptions are meant for, ehm, exceptional cases. Using them for controlling normal control flow is not only obscuring the intent of the code (which would be enough to disqualify it already), but also is much slower, since throwing and catching exceptions is costly.

    The standard idiom (in Java5 and above) is using a foreach loop:

    for (int i : intArr) {
      System.out.println(i);
    }
    
    0 讨论(0)
  • 2020-12-06 17:42

    Reaching the end of an array is not an exceptional case. You know the length before you start looping, so just use a standard idiom.

    for(int i = 0; i < intArr.length; ++i) {
        System.out.println(intArr[i]);
    } 
    
    0 讨论(0)
  • 2020-12-06 17:44

    Catching exceptions is only a bad practice when it concerns a RuntimeException. The ArrayIndexOutOfBoundsException which you're trying to catch there is one.

    RuntimeExceptions identify programmatically recoverable problems which are caused by faults in code flow. You should not fix them by catching them, but by writing proper code and making use of flow control statements like if/else, while, for, etc.

    See also:

    • When to throw which exception?
    • Exceptions tutorial
    0 讨论(0)
  • 2020-12-06 17:48

    Eating exceptions the way you do is usually considered a bad practice : if you don't have to do any further treatment, you can log it.

    0 讨论(0)
提交回复
热议问题