-4

I have a few Exception classes that I built (which currently don't inherit from any class). I want to do a "try" and "catch" and in the catch print the error message which relates to the specific Exception class that has been thrown. Is there a possible way to do

try(something){
}
catch(){
   System.out.println(error.printMsg());
}

and that according to the excpetion, it would print the msg that related to the class?

Edit: I will refine my question, in try and catch, can be thrown a few possible Exception classes that I built, I want instead of doing :

catch(Error1){
System.err.println(Error1.ERROR_MSG);
}
catch(Error2){
System.err.println(Error2.ERROR_MSG);
}

to do :

catch(ERROR1 | ERROR2){
System.out.println(GenarlError.ERROR_MSG)
// maybe to do a class that all the Excpetion will inhirt from, and somehow 
//do upcasting,or something like that (but If I will do upcasting it would 
//print the message or the right class?
}
Georg
  • 29
  • 6

2 Answers2

1

If you want to catch multiple exceptions and do something different with each one, you can write code such as:

try {
    // Execute code
} catch(MyException e) {
    System.out.println(e.getMessage());
} catch(MyNextException e) {
    System.out.println(e.getMessage());
}

If you want to do the same thing with each exception you can catch them a more succinct way:

try {
    // Execute code
} catch(MyException | MyNextException e) {
    System.out.println(e.getMessage());
}

Note, that to do this though your Exceptions will need to extend Exception in some form

D.Salter
  • 221
  • 1
  • 4
  • I want when catching to print a custom message which related to the class – Georg Jun 01 '18 at 15:44
  • @Georg Try to use this: `catch(MyException | MyNextException e) { System.out.println(e.getMessage()) }` or alternate use the method `e.printStackTrace()` – 0x1C1B Jun 01 '18 at 15:48
  • @Georg - I've changed the code to highlight how you can print out a message depending on each exception. If this is logging information, its a better practice to use a logger than println() however. – D.Salter Jun 01 '18 at 15:57
  • @0x1C1B Thanks, it works, just needed to add interface – Georg Jun 01 '18 at 16:08
  • @D.Salter thanks to you too, I needed a custom msg, so logger won't help, but the same idea that u and 0x1C1B offered work well for my custom msg. – Georg Jun 01 '18 at 16:13
0

in catch block you must have type of exception:

public class Main throws Exception{
try{
  ...
}
catch(Exception error){
   System.out.println(error.printStackTrace());
}
}

If you want to make your own exception make it and extend the Exception class. And on your main class put throws exception

  • Why do you added the exception to the method signature? Without re-throwing the caught exception, this method won't throw an exception... – 0x1C1B Jun 01 '18 at 15:42