MyCustomRuntimeException

MyCustomRuntimeException

基本上,我的代码在下面。考虑到这是代码的“测试”状态。最初的问题是调用init()到另一个类,该类引发了已检查的异常。 try / catch块捕获了此抛出,然后在尝试创建异常时应用程序失败。为了清楚起见,已删除所有内容,因为问题出在“ MyCustomRuntimeException”创建中。

@Component
public class ClassName {

  public ClassName() {
    //minor, non problematic operations.
  }

  @PostConstruct
  public void init() {
    throw new MyCustomRuntimeException("AAAAAAAH");
  }

}


MyCustomRuntimeException的定义如下:

public class MyCustomRuntimeException extends RuntimeException {

  public MyCustomRuntimeException (String message) {
    super(message);
  }
}


并且,在创建使用此类的类时出现“ UnsatisfiedDependencyException”异常。控制台指向抛出新MyCustomRuntimeException的行,但我并没有真正了解正在发生的事情。

另外,“ MyCustomRuntimeException”作为常规异常开始,但是我看到了I should throw a RunTimeException instead because the @PostConstruct forbids checked exceptions to be thrown。而且我还尝试抛出一个标准的RunTimeException,但是没有运气。

所以,我在这里一无所知。关于为什么我不能引发此异常的任何想法?

最佳答案

需要正确创建上下文中的每个bean。发生错误时,bean的创建将停止/失败,并且上下文(或换句话说,您的应用程序)将不会启动。

您得到一个UnsatisfiedDependencyException的原因是创建了ClassName bean,因为另一个bean需要它。构造ClassName之后,它将调用@PostConstruct bean的ClassName,并且由于异常而失败。因此不会创建该实例,因此为UnsatisfiedDependencyException

UnsatisfiedDependencyException的根本原因将是您自己的初始化方法引发的异常。

09-05 03:31