How to throw an Exception when your method signature doesn't allow to throw Exception?

后端 未结 3 1613
感动是毒
感动是毒 2021-01-31 18:58

I have a method like this:

public void getSomething(){
...
}

I want to throw an Exception inside getSomething(). The

3条回答
  •  逝去的感伤
    2021-01-31 19:41

    I don't know what you were trying to do. You could just throw an unchecked exception inside your method and then test using JUnit like in my example below.

    public void getSomething() {
        throw new RuntimeException();
    }
    

    JUnit 4 test example:

    @Test
    public void testGetSomething() {
        try {
            getSomething();
            fail("Expecting RuntimeException!");
        } catch (Exception e) {
            Logger.getLogger("test").info("Exception was caught: " + e.getClass());
        }
    }
    

提交回复
热议问题