Catching Java errors

前端 未结 4 798
栀梦
栀梦 2020-12-08 14:58

I\'ve heard that catching java.lang.Error is considered bad practice. I\'m currently loading a .dll that is not guaranteed to be on the PATH, and would like to

4条回答
  •  囚心锁ツ
    2020-12-08 15:00

    If you are coding defensively and can recover from an issue, then it's not a Java Error. If such an issue is not very likely, then create a subclass of Exception and throw and catch that. If such an issue is likely, then it shouldn't even throw an Exception; but, should be part of the regular code flow.

    try {
      if (config.hasCustomDLL()) {
        System.load(config.getCustomDLL());
      } else {
        System.loadLibrary(Config.DEFAULT_DLL);
      }
    } catch (UnstatisfiedLinkError e) {
      System.out.println("Error loading DLL: " + e);
    }
    

    Errors are meant for really bad failures, not recoverable "failures" which really aren't even failures if there is a suitable workaround. Don't overload the system designed to handle failure with what amounts to an ability to configure the system multiple ways.

提交回复
热议问题