Reputation: 19
My question is, that I have no clue how to handle exceptions in the @before block of Junit4. 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?
Upvotes: 0
Views: 792
Reputation: 96444
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. That way you retain the original stacktrace that shows what happened.
Upvotes: 1