0

Can anyone explain what the purpose is of creating your own Exception class by subclassing java.lang.Exception?

Why can't you just make your own traditional class that deals with Exceptions?

Can anyone provide an example about why it's useful to subclass Exception or Throwable?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

3 Answers3

2

It's useful because it gives you more granular control over the types of exceptions your application throws in case of error. If everything talkes in terms of very general exceptions you are forced to rely on the stringly typed info in the error message. It's much better to be able to give a typed exception that you can check against

TGH
  • 38,769
  • 12
  • 102
  • 135
2

subclassing java.lang.Exception is useful when you're building a piece of code that can throw different Exceptions, for example, when you open a file, you can get FileNotFoundException or IOException... know imagine you are downloading that from a specific URL, so you can get MalformedURLException and so on. Imagine such scenario but with very program-specific exceptions.

Doing stuff like

try{
   ....
}catch(MySubclassedException1 ex){
   ....
}catch(MySubclassedException2 ex){
   ....
}catch(MySubclassedException3 ex){
   ....
}

Will be much more efficient and cleaner than

try{
   ....
 }catch(Exception ex){
   if(ex.getMessage().equals("Message1")){
      ...
   }else if(ex.getMessage().equals("Message2")){
      ...
   }else if(ex.getMessage().equals("Message3")){
      ...
   }
 }

Hope it helps.

Javier Enríquez
  • 630
  • 1
  • 9
  • 25
1

InvalidUserCredentialsException. Anyone receiving that exception will know what it is. Also, you can check to see if the exception is of type whatever and handle it based on the type. For example, if an exception is raised and you realize it's of type InvalidUserCredentialsException, you know to redirect to the login screen.

JeffRegan
  • 1,322
  • 9
  • 25