Home > Mobile >  Which exception should I throw when switching over type?
Which exception should I throw when switching over type?

Time:10-19

I have a type hierarchy where classes B and C inherit abstract class A.

I have a code block like this:

if (someVar instanceof B) {
  return "b";
} else if(someVar instanceof C) {
  return "c";
} else {
  throw new Exception("Missing type handling…");
}

I would like to know if there is an appropriate exception for this in Java, like IllegalArgumentException.

CodePudding user response:

IllegalArgumentException is fine.

IllegalArgumentException extends RuntimeException

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

  •  Tags:  
  • java
  • Related