BAEL-2516 catching errors in catch block (#6761)

This commit is contained in:
binary-joe 2019-05-24 18:12:40 +02:00 committed by Grzegorz Piwowarek
parent 93dfb77f1f
commit d373336b74
2 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1,15 @@
package com.baeldung.error;
public class ErrorGenerator {
public void throwException() throws Exception {
throw new Exception("checked");
}
public void throwRuntimeException() {
throw new RuntimeException("unchecked");
}
public void throwError() {
throw new Error("unchecked");
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.error;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ErrorGeneratorUnitTest {
private ErrorGenerator errorGenerator;
@Before
public void setUp() {
errorGenerator = new ErrorGenerator();
}
@Test
public void whenCheckedException_thenIsCaughtByCatchException() {
try {
errorGenerator.throwException();
} catch (Exception e) {
// caught! -> test pass
}
}
@Test
public void whenUncheckedException_thenIsCaughtByCatchException() {
try {
errorGenerator.throwRuntimeException();
} catch (Exception e) {
// caught! -> test pass
}
}
@Test(expected = Error.class)
public void whenError_thenIsNotCaughtByCatchException() {
try {
errorGenerator.throwError();
} catch (Exception e) {
Assert.fail(); // errors are not caught by catch exception
}
}
@Test
public void whenError_thenIsCaughtByCatchError() {
try {
errorGenerator.throwError();
} catch (Error e) {
// caught! -> test pass
}
}
}