Search code examples
javaexceptionstatic-methods

Error when trying to use a custom exception in a static method


I have a java class called Exercise08.java. In this class I made the inner class HexFormatException which extends NumberFormatException.

public class HexFormatException extends NumberFormatException {
  public HexFormatException() {
    super();
  }
}

I also have the static method hexToDecimal(String) which is supposed to throw a HexFormatException error if the String is not a hexadecimal.

/** Converts hexadecimal to decimal.
  @param hex The hexadecimal
  @return The decimal value of hex
  @throws HexFormatException if hex is not a hexadecimal
*/
public static int hexToDecimal(String hex) throws HexFormatException {
  // Check if hex is a hexadecimal. Throw Exception if not.
  boolean patternMatch = Pattern.matches("[0-9A-F]+", hex);
  if (!patternMatch) 
    throw new HexFormatException();

  // Convert hex to a decimal
  int decimalValue = 0;
  for (int i = 0; i < hex.length(); i++) {
    char hexChar = hex.charAt(i);
    decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
  }
  // Return the decimal
  return decimalValue;
}

Instead I get this error message:

enter image description here

I'm really confused about how to fix this. Everything works fine if I throw a NumberFormatException, but why doesn't it work for my custom exception?


Solution

  • To use inner class in static method it must be static too.

    public static class HexFormatException extends NumberFormatException {
      public HexFormatException() {
        super();
      }
    }