Which is better/more efficient: check for bad values or catch Exceptions in Java

前端 未结 11 1623
旧巷少年郎
旧巷少年郎 2020-12-15 08:11

Which is more efficient in Java: to check for bad values to prevent exceptions or let the exceptions happen and catch them?

Here are two blocks of sample code to ill

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 08:28

    Well, exceptions are more expensive, yes but for me, its about weighting the cost of efficiency vs bad design. unless your use case demands it, always stick to the best design.

    the question really is, when do you throw an exception? in exceptional situations.

    if your arguments are not in the range that you're looking for, i'd suggest returning an error code or a boolean.

    for instance, a method,

    public int IsAuthenticated(String username, String password)
    {
    
         if(!Validated(username,password)
         {
              // just an error
              // log it
              return -2;   
         }
    
         // contacting the Database here
         if cannot connect to db
         {
              // woww this is HUUGE
              throw new DBException('cannot connect'); // or something like that
         }
    
         // validate against db here
         if validated, return 0;
    
        // etc etc
    
    }
    

    thats my 2 cents

提交回复
热议问题