Reputation: 1069
Can we create an custom exception for a class Level. For example I have a Class A, now when I create a given object or When I call a given method, I would like yo throw my custom exception.
Upvotes: 0
Views: 431
Reputation: 45005
You have two kind of exceptions checked
and unchecked
exceptions.
Unchecked
exceptions are the sub classes of RuntimeException
, those exceptions don't need to be added explicitly in your method/constructor description, calling code doesn't have to manage it explicitly with a try/catch
block or by throwing it.Checked
exceptions are the sub classes of Exception
but not the sub classes of RuntimeException
, those exceptions need to be added explicitly in your method/constructor description, calling code have to manage it explicitly with a try/catch
block or by throwing it.Depending of your need, you will chose one of the two possibilities, if you want to enforce calling code to manage it, use checked
exceptions otherwise use unchecked
exceptions.
Unchecked
exceptions
How to create it:
public class MyException extends RuntimeException {
...
}
How to use it:
public void myMethod() {
...
if (some condition) {
throw new MyException();
}
...
}
Checked
exceptions
How to create it:
public class MyException extends Exception {
...
}
How to use it:
public void myMethod() throws MyException {
...
if (some condition) {
throw new MyException();
}
...
}
You can find more details about exceptions here
Upvotes: 2
Reputation: 44496
This is the easiest way to create your own Exception
:
public class LevelException extends Exception {
public LevelException(String message) {
super(message);
}
}
Upvotes: 2