My code
networkService.setOnFailed(event -> {
Throwable exception = event.getSource().getException();
System.out.println(exception);
}
)
makes it hard to verify that my exception is a certain type.
When I print it, I get this:
myCustomException: File C:\Users\...\Documents\...\test\...zip does not exist or is not a regular file
and I would like to only get myCustomException
to then only do something if it is indeed myCustomException
and not another exception.
I guess I could use regular expressions to only get this out of this String but I think there might be a method to do this "more cleanly" if that makes sense. Especially if there is another exception that might respond poorly to my made-at-home regular expression parser.
CodePudding user response:
No, it isn't. It's a Throwable
- your code says it, right there: Throwable exception
.
The println
method has a few variants; one for each primitive (such as double
and int
); clearly not relevant here. Then one for String
, that part is obvious. Finally, one for any Object
- and what that will do is invoke the toString()
method on the object you pass to it, and then print that.
That's what is happening here (as Throwables are also objects) - you're seeing the toString output. You should never use toString output as meaningful, it's a debugging aid, you should not be parsing it.
Here are a few things you can do:
if (exception instanceof MyCustomException) {
MyCustomException customEx = (MyCustomException) exception;
customEx.getCustomStuff();
}
exception.getClass() == MyCustomException.class // would be true
exception.getMessage();
and so on.