Java exception 是 event.getSource().getException() 之后的字符串,很难捕获,因为必须进行解析

Java exception is a string after event.getSource().getException() and hard to catch because has to be parsed

我的代码

        networkService.setOnFailed(event -> {
        Throwable exception = event.getSource().getException();
        System.out.println(exception);
        }
        )

很难验证我的异常是某种类型。 当我打印它时,我得到这个: myCustomException: File C:\Users\...\Documents\...\test\...zip does not exist or is not a regular file 我只想得到 myCustomException 然后只做一些事情,如果它确实是 myCustomException 而不是另一个例外。

我想我可以使用正则表达式只从这个字符串中得到它,但我认为如果有意义的话,可能有一种方法可以“更干净地”做到这一点。特别是如果有另一个异常可能对我自制的正则表达式解析器反应不佳。

不,不是。这是一个 Throwable - 你的代码说了,就在那里:Throwable exception.

println 方法有几个变体;每个原语一个(例如 doubleint);显然这里不相关。然后是 String,那部分是显而易见的。最后,一个用于 any Object - 它将做的是在传递给它的对象上调用 toString() 方法,然后打印它。

这就是这里发生的事情(因为 Throwable 也是对象)- 您看到的是 toString 输出。你应该永远不要使用有意义的 toString 输出,它是一种调试辅助工具,你不应该解析它。

您可以执行以下操作:

if (exception instanceof MyCustomException) {
  MyCustomException customEx = (MyCustomException) exception;
  customEx.getCustomStuff();
}

exception.getClass() == MyCustomException.class // would be true
exception.getMessage();

等等。