2. Usage2. Usage3. API Reference
PreviousUpNext

Exceptions
Unreachable
The Java compiler typically cannot detect unreachable cases in, for example, switch statements:
enum T
{
  A,
  B,
  C
}

int f(
  final T t)
{
  assert t != null;

  switch (t) {
    case A:
    {
      return 1;
    }
    case B:
    {
      return 2;
    }
    case C:
    {
      return 3;
    }
  }
}
The function f will fail to compile due to a missing return statement; even though all possible cases of T are handled, the compiler is not sufficiently intelligent to determine this. Naive developers might try to add a default case, but this makes the code fragile with respect to modification; if someone adds an extra value to T, the code silently becomes incorrect. The correct course of action is to explicitly mark the unreachable code with an exception that unambiguously states the intention:
enum T
{
  A,
  B,
  C
}

int f(
  final T t)
{
  assert t != null;

  switch (t) {
    case A:
    {
      return 1;
    }
    case B:
    {
      return 2;
    }
    case C:
    {
      return 3;
    }
  }

  throw new UnreachableCodeException();
}
The code now compiles. The code is robust in the face of later modification of T. Anyone reading the code understands that the original writer expected the code to be unreachable. Anyone running the code and somehow managing to reach the unreachable section is greeted with an unambiguous exception that states that a bug has been discovered (and the stack trace will indicate exactly where this happened).
Unimplemented code
Most Java development environments will automatically produce empty method stubs when the programmer attempts to implement an interface. The generated methods typically look something like:
@Override void someInterfaceMethod()
{
  // TODO: Auto-generated method stub
}
The programmer doesn't always have a complete implementation ready immediately, and unfortunately nothing stops anyone from running the as-yet unimplemented methods. The correct course of action is to explicitly mark this unimplemented code with an exception type that unambiguously states the nature of the code:
@Override void someInterfaceMethod()
{
  // TODO: Auto-generated method stub
  throw new UnimplementedCodeException();
}
Discovering unimplemented code is now as simple as searching for uses of UnimplementedCodeException in the codebase. Anyone managing to execute unimplemented code will be greeted with an exception that states exactly which code is unimplemented. Most development environments can be instructed to automatically generate code that throws UnimplementedCodeException exceptions as in the above example.

PreviousUpNext
2. Usage2. Usage3. API Reference