I am trying to override ArrayIndexOutOfBoundsException with my custom exception NoArgumentException. The program compiles and runs but I am not getting the result as I want it. It must print "Please enter the argument at command line" if no argument is supplied at command line, but it is printing ArrayIndexOutOfBoundsException.
No, you are trying to extend Exception with your NoArgumentException. If you throw an ArrayIndexOutOfBoundsException and print it out, the class name is part of the printout.
When you create your own Exceptions you should consider what the purpose of your Exception will be and use that to choose the superclass. A NoArgumentException is not an ArrayIndexOutOfBoundsException, so I think that particular inheritance hierarchy is inappropriate. Also the name of the class, MyException is poorly‑chosen because it is not an Exception of any kind. ExceptionDemo might be a better name.
What happens if you require a content to args (as you are doing at line 35) and don't pass any arguments, you will be trying to get an element out of a 0‑element array. You would need to start the class with this sort of instruction (assuming you change it to ExceptionDemo)
Or you move the use of args until after your test for args.length == 0
Joined: Jul 19, 2014
Attached is the screenshot of the exception I get if no argument is passed at command line.
I changed the name as you suggested.
I have extended ArrayIndexOutOfBoundsException as well but it did not work. Kindly check
Joined: Oct 13, 2005
I have corrected the code tags: the code goes after [code=java] and before [/code]
You don't appear to have taken any notice of my other two suggestions from earlier, however. Provide arguments or move the use of args. Look at lines 35-36.
The command() and checkFood() methods do not throw any Exceptions: take the throws clauses off.
You can't override ArrayIndexOutOfBoundsException with your own custom implementation. Extending a class does not cause your subclass to be used instead of the original.
If you access an array index that is out of bounds you get an ArrayIndexOutOfBoundsException, and you can't change that without rewriting the Java API.
What you can do is catch the Exception that is thrown, and the rethrow your own type.
Be sure to make sure your new exception can accept a Throwable as a constructor parameter, and pass that to the super constructor in Exception. That will add it as the cause of your custom Exception, and maintain the full stack trace.