Reputation: 28907
I'm a little confused because I want to be able to throw a custom exception in Java. To do this inside a function, I have to add throws MyException
to the header of the function.
And then anything that calls that function in turn must add throws MyException
or have a try-catch block. But why is this?
For example, when creating a Stack in java and calling the pop function, I don't have to have a try-catch and yet the pop method in Java throws a NoSuchElementException
(or w/e it is) if there isn't an element on the stack.
Upvotes: 2
Views: 2439
Reputation: 6934
See my answer to this question.
As a general rule of thumb, when deciding whether or not to create a custom exception class, I try and use the built-in exception classes as much as possible, where it makes sense to do so, e.g. IllegalArgumentException
, etc.
Here is an example of how to create a custom RuntimeException
, which, as you have discovered, will not require a try/catch/finally
block, or a throws
clause.
public class MyRuntimeException extends RuntimeException {
public MyRuntimeException() {
super();
}
public MyRuntimeException(String message) {
super(message);
}
}
public class MyClass {
public void go(int val) {
if(val <= 0) throw new MyRuntimeException("Val must be greater than 0.");
}
}
Upvotes: 0
Reputation: 46408
NoSuchElementException
is a RuntimeException
(un-checked exception) and we don't need to handle or declare RuntimeException
S, thus the compiler wont complain, but instead throw it at runtime.
In the case of checked exceptions i.e., all the exceptions which are not subtypes of RuntimeException
, the compiler will check for a suitable catch
clause, enabling the program to continue its course of execution, after performing the operations within the catch
; to do this, you need to handle them using try/catch
blocks or declare them using the throws
clause - delegating the responsibility of handling the exception higher up the call chain. If your custom exception is not a RuntimeException
rules of checked exceptions apply to your custom exception as well.
Checked exceptions ---> Forced by the compiler to handle or propagate
Un-checked exceptions ---> Not checked by the compiler thus appears at runtime
Upvotes: 4
Reputation: 43738
Java has so called checked exceptions and unchecked exceptions. A checked exception must be declared in method signature, an unchecked exception does not need to be declared.
If you want to define an unchecked exception yourself derive it from RuntimeException
insted of Exception
.
Upvotes: 3
Reputation: 10997
you are supposed to throw or try-catch all checked Exceptions , its not required for RunTimeException
and exception that you are talking about is a RuntimeException
Upvotes: 0