Recently i attended an interview. one of the questions asked in technical interview round is "how can you throw a user defined exception using single statement". i wrote the code as
class MyException extends Exception{
public MyExeption(String err){
super(err);
}
class sample{
public static void main(String a[]){
throw new MyException("Error");
}
but he said that i used 2 statements 1 for throw statement and other for super() statement. what is the answer. plese clear my doubt. thank you
I am sure that the interviewer was looking for you to extend Exception anonymously:
throw new Exception("Error") {
// Here is what makes the exception user-defined.
// You do not need to override anything, but if you want, you can:
public String getMessage() {
return "Here is your user-defined exception!";
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With