Home  >  Article  >  Java  >  How to avoid unnecessary use of checked exceptions in Java?

How to avoid unnecessary use of checked exceptions in Java?

WBOY
WBOYforward
2023-04-21 20:10:071289browse

Avoid unnecessary use of checked exceptions

Checked exceptions force the caller to handle exception conditions, because if not, the compiler will complain. Overuse of checked exceptions places the burden on the caller to handle exception conditions. So you should use checked exceptions when necessary. The rule of thumb for using checked exceptions is that when the exception cannot be avoided by checking preconditions, the caller can take some useful action to handle the exception.

Commonly used runtime exceptions themselves are examples of not overusing checked exceptions. Common runtime exceptions are: ArithmeticException, ClassCastException exception, throw: IllegalArgumentException, IllegalStateException exception, IndexOutOfBoundExceptions, NoSuchElementException exception, and NullPointerException exception.

In the method below, there is not much the caller can do when propertyName is not one of the target conditions, so a runtime exception is thrown.

@Override
public Object get(String propertyName) {
  switch (propertyName.hashCode()) {
    case 842855857:  // marketDataName
      return marketDataName;
    case -1169106440:  // parameterMetadata
      return parameterMetadata;
    case 106006350:  // order
      return order;
    case 575402001:  // currency
      return currency;
    case 564403871:  // sensitivity
      return sensitivity;
    default:
      throw new NoSuchElementException("Unknown property: " + propertyName);
  }
}

The above is the detailed content of How to avoid unnecessary use of checked exceptions in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete