Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throw user defined exception in single statement in java

Tags:

java

exception

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

like image 809
praveen kumar Avatar asked May 12 '26 21:05

praveen kumar


1 Answers

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!";
    }
};
like image 141
Sergey Kalinichenko Avatar answered May 14 '26 10:05

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!