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.
2 Answers
You have two kind of exceptions checked and unchecked exceptions.
Uncheckedexceptions are the sub classes ofRuntimeException, those exceptions don't need to be added explicitly in your method/constructor description, calling code doesn't have to manage it explicitly with atry/catchblock or by throwing it.Checkedexceptions are the sub classes ofExceptionbut not the sub classes ofRuntimeException, those exceptions need to be added explicitly in your method/constructor description, calling code have to manage it explicitly with atry/catchblock 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