简体   繁体   English

Junit 之前的异常处理

[英]Junit exception handling in before

My question is, that I have no clue how to handle exceptions in the @before block of Junit4.我的问题是,我不知道如何处理 Junit4 的 @before 块中的异常。 For example:例如:

@Before
public void init() throws Exception{
    b=new FirstNationalBank();
    acc1=b.openAccount();
    acc2=b.openAccount();
    try{
    b.deposit(acc1, 1500);
    b.deposit(acc2, 12000);
    }catch(Exception ex) {
        throw new Exception();
    }
}

The way I did this doesn't seem right, or maybe It is, but I am not sure, whether this will throw an error or how It will react when an unexpected exception or an exception of any kind gets thrown.我这样做的方式似乎不正确,或者可能是正确的,但我不确定这是否会引发错误,或者当引发意外异常或任何类型的异常时它会如何反应。

How would you handle It?你会如何处理它?

Catching and re-throwing is pointless here, and in this case you're losing the original stack trace that tells you what went wrong.在这里捕获和重新抛出是没有意义的,在这种情况下,您将丢失告诉您出了什么问题的原始堆栈跟踪。 Just let stuff be thrown:只是让东西被扔掉:

@Before
public void init() throws Exception{
    b=new FirstNationalBank();
    acc1=b.openAccount();
    acc2=b.openAccount();
    b.deposit(acc1, 1500);
    b.deposit(acc2, 12000);
}

The test framework will catch and report any exceptions.测试框架将捕获并报告任何异常。

If you do need to catch something and rethrow, remember to pass the original Exception to the new exception, a throwable has a member called cause that can hold another throwable.如果您确实需要捕获某些内容并重新抛出,请记住将原始异常传递给新异常,一个throwable 有一个名为cause 的成员可以保存另一个throwable。 That way you retain the original stacktrace that shows what happened.这样你就可以保留显示发生了什么的原始堆栈跟踪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM