Why, when I am testing that a method throws an exception and the method throw an exception, does the test stop?

StackOverflow https://stackoverflow.com/questions/22384572

Question

I have a unit test that tests if method throws an exception when condition is present, and method does throws exception as expected.

- (void)testMethodThrowsWhenConditionIsPresent {
    XCTAssertThrows([Foo methodWithCondition: condition], @"Condition is true, method should throw exception");
}

Here is the exception source:

- (void)methodWithCondition:(someType)condition {
    if (condition) {
        [NSException raise: @"condition is true!" format: @"condition is true!"];
    }
}

Why does the test stop at the line the exception is thrown? The test does not go on, it stops at that line, when I expect it to continue and return 1 from XCTAssertThrows(), making the test succeed. The test instead stops with Xcode bringing me to the line it was thrown, with a green `Thread 1: breakpoint 1.1' and the debugger appearing in the console.

Was it helpful?

Solution

Why does the test stop when the execution is thrown?

Because you have a breakpoint, which stops execution.

Why, after removing the breakpoint, does my application crash when the exception is thrown?

Because you have an unhandled exception. Unhandled exceptions cause your program to crash.

How can I handle an exception so it won't crash my program?

The easy answer to this question is to simply NOT throw an exception. In other programming languages, like Java, this is perfectly standard. But in Objective-C, we don't really do exceptions. In Objective-C, exceptions should be saved for TRULY exceptional behavior.

With that said, and a strong suggestion for you to find another way to handle whatever it is you're trying to handle, this is how you handle an exception in Objective-C:

@try {
    // code that could throw an exception
}

@catch (NSException *e) {
    // handle the exception...
}

@finally {
    // post try-catch code, executed every time
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top