bijiDango
bijiDango

Reputation: 1596

surround "throw new Exception()" with try catch

throw new Exception();

If you put this statement in a method, you should either add throws Exception after the method name. Or, you can surround the statement with try-catch.

try {
    throw new Exception();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

But what is it the point here? The compiler permit it, so I just want to know if it is designed intentionally. I am curious.

Upvotes: 2

Views: 2463

Answers (1)

Buddhima Gamlath
Buddhima Gamlath

Reputation: 2328

Actually, this is useful in some scenarios.

Say, you want to perform a series of tasks and if any one of them fails, you want to abort the sequence and do some other task.

It is true that you can do the same with a series of if statements, but this provides another way to do it.

try{
// do task 1
// if failed, throw new Exception("Task 1 Failed");

// do task 2
// if failed, throw new Exception("Task 2 Failed");

// do task 3
// if failed, throw new Exception("Task 3 Failed");

...

}catch(Exception e){
 // System.err.println(e.getMessage());
 // do somthing else
}

Upvotes: 3

Related Questions