This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
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)
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.