Throwing exceptions in Java

后端 未结 11 997
萌比男神i
萌比男神i 2020-12-30 16:23

I have a question about throwing exceptions in Java, a kind of misunderstanding from my side, as it seems, which I would like to clarify for myself.

I have been read

11条回答
  •  滥情空心
    2020-12-30 16:27

    The reason why that would seem as nonsense ( throwing and catching in the same method ) is because that would be an scenario of using exceptions for flow control. If you already have enough data as to identify the condition where the exception should be thrown then you could use that information to use a condition instead.

    See below:

    1) Throwing and catching exception in same method ( wrong )

    public void method() { 
        try {    
            workA...
            workA...
            workA...
            workA...    
            if( conditionIvalid() && notEnoughWhatever()  && isWrongMoment() ) { 
                throw new IllegalStateException("No the rigth time" );
            }
            workB...
            workB...
            workB...
            workB...
        } catch( IllegalStateException iee ) { 
            System.out.println( "Skiped workB...");
        }
        workC....
        workC....
        workC....
        workC....
    }
    

    In this scenario the exception throwing are used to skip the section "workB".

    This would be better done like this:

    2) Using condition to control flow ( right )

    public void method() { 
        workA...
        workA...
        workA...
        workA...    
        if( !(conditionIvalid() && notEnoughWhatever()  && isWrongMoment() ) ) { 
            //throw new IllegalStateException("No the rigth time" );
            workB...
            workB...
            workB...
            workB...
    
        }
        workC....
        workC....
        workC....
        workC....
    }
    

    And then you can refactor the condition:

        if( !(conditionIvalid() && notEnoughWhatever()  && isWrongMoment() ) ) { 
    

    for

        if( canProceedWithWorkB() ) {
    

    implemented as:

      boolean canProceedWithWorkB() {  
          return !(conditionIvalid() && notEnoughWhatever()  && isWrongMoment() );
      } 
    

提交回复
热议问题