When to use exceptions in Java (example)

前端 未结 10 1746
既然无缘
既然无缘 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:49

    Exceptions are for exceptions in the code. Not for standard cases.

    however, there are one more serious issue with your code, it is slower the it would be without the use of exception. Creating the exception, throwing the exception and catching the exception takes additional CPU and MEMORY.

    Also the code gets harder to read for other programmers that only expect Exceptions to be thrown on error cases.

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

    Only in exceptional situations like,

    • when a method cannot do what it is supposed to do
    • not to control the execution flow
    0 讨论(0)
  • It's wrong because you know that eventually the loop will reach the last element of intArr, so there's nothing exceptional in this, you're actually expecting this behaviour.

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

    As always "it depends" and you will find many differing opinions. Here's mine

    • Exceptions fall into two general categories.
      • Things you can reasonably anticipate and handle (FileNotFoundException)
      • Things you generally don't antipicate assuming perfect code (ArrayIndexOutOfBounds)

    You would expect to generally handle the first category and not the latter. The latter is usually programming errors.

    Your example falls into the latter case, a programming error. The exception is intended to give good information about the failure at runtime, not act as a control flow.

    Some people will say that the first is checked exceptions and the second is unchecked. I would disagree with that. I almost always find checked exceptions a pain in reality as you almost always end up doing catch/wrap/rethrow to another exception type. When throwing exceptions and defining my own exception classes I almost always use unchecked.

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