Reputation: 865
In C++ I can declare a function which can not further throw exceptions as under
int myfunction (int param) throw(); // no exceptions allowed
Can I have such declaration in Java programming language?
Upvotes: 1
Views: 140
Reputation: 308131
No, any method can always throw an unchecked exception (RuntimeException
and Error
).
You only need to list checked exceptions (Exception
subclasses that don't derive from RuntimeException
) in the method declaration.
And an ugly side-note: while the compiler does check that no checked exception is thrown that is not declared, you can work around that with some ugly tricks (that's sometimes called a sneaky throw, Project Lombok supports it explicitly).
Upvotes: 5
Reputation: 1770
There's a way by which you can ensure that an exception will not at all be thrown to the previous layer. Simply put all your code in a try catch statement, so that even though any exception occurs in the method, it will always be catched.
But, remember it will only ensure that the exception will not propogate to the previous(calling) layer.It will surely not ensure that the exception will not at all occur in the method body
Upvotes: 0
Reputation: 8874
No, not in that sense. You can declare a function to not throw an exception (simply don't include the throws keyword), but you cannot prevent a function from throwing any exception at all. Imagine you will have division by zero in that function - the program's behaviour would be then undefined.
Upvotes: 0