0

I want to throw a specific exception for a block of code without creating a new class. Is there any way to throw an exception with a specific code and catch it with this code identifier?

try {
    //Do something
    if(somevalue)
        throw new Exception(667);
} catch (Exception e) {
    if(e.getCode() == 667) {
     //Do something
    }
    System.out.println("Something went wrong.");
}
chatzich
  • 1,083
  • 2
  • 11
  • 26
  • Hmmm...if you want to use the default Exception then you can use ```e.getMessage() == "667"``` by throwing ```throw new Exception("667");``` – Runcorn Apr 18 '20 at 14:54
  • 2
    Why not throw a more specific exception? This would be the way to go ... – Seelenvirtuose Apr 18 '20 at 14:57
  • @Runcorn [do not compare `String`s (or really any object) with `==` unless you know exactly what you are doing](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – Turing85 Apr 18 '20 at 15:10
  • why do you even need to use try catch if you have already identified "someValue" will need to "Do something" ? this is just over complication – mark ortiz Apr 18 '20 at 15:17
  • Thanks @Turing85 for the reminder. – Runcorn Apr 18 '20 at 15:19

1 Answers1

-1

I am not sure what is your use case. I assume your want to use codes to define some sort of state of your application so you can use IllegalStateException

You can use

try {
    //Do something
    if(somevalue)
        throw new IllegalStateException("667")
} catch (IllegalStateException e) {
    if("667".equalIgnoreCase(e.getMessage())) {
     //Do something
    }
    System.out.println("Something went wrong.");
}catch(Exception e){
     System.out.println("Unexpected error");
}

cp392
  • 31
  • 1
  • 9
  • the code is already identified in the try block so why the need to catch block and why the need of new classes? not a good case to follow – mark ortiz Apr 18 '20 at 15:01
  • @mark I have seen planty of use cases where you do some validation and throw exception with some error code. We used our own exception class. In these case user doesn't want to create new class but I am sure error code represent either bad argument or bed state of application so I picked one for example. Plus you dont want throw & catch Exception and do error validation on that. Keep it separate for more wide range of other Exception could occur. Also when you have some sort of codes defined for each error means user is going to return some more details response then just throw exception. – cp392 Apr 18 '20 at 16:53
  • I hope my explanation was enough to rething your negative vote. – cp392 Apr 18 '20 at 16:57