0

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?

Mr.Young
  • 324
  • 5
  • 14

2 Answers2

2

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

public static class HexFormatException extends NumberFormatException {
  public HexFormatException() {
    super();
  }
}
Alexandr Ivanov
  • 389
  • 1
  • 5
  • 7
1

You've made HexFormatException an inner class which means it belongs to an enclosing instance. In at static method there is no default enclosing instance so you get this error.

A simple fix is to declare the class with static:

public static class HexFormatException ...
Joni
  • 108,737
  • 14
  • 143
  • 193