As a newbie Java programmer will it be common that I'll need to create my own Exception classes so that I should spend time learning it?
Reasonably common. Definitely something you should know how to do.
Gary Charles wrote:
Did I do this correctly? Why didn't "System.out.println("In BadException now");" in my BadException class execute?
Looks alright. The message didn't print because you never call the BadException method. Do you know the difference between a method and a constructor ?
Gary Charles wrote:
Plus any general comments that might you might have.
Have a look at the Exception class. You'll notice it has a lot of constructors. You don't need to have all those constructors in your class, but you should definitely know what each of them is for, so you can make an informed decision about whether to include them in your class or not. You can of course have constructors of your own that don't match any of the Exception class constructors.
Also have a look at some of the sub classes of Exception and try and work out how and why they are different to Exception. This may give you some indication of when you should create your own exception class and when you should use an existing one.
posted 6 years ago
Thank-you for the tip(s)!
I had forgotten that constructors do not have a return type. I removed the void return type and am getting what I expect.
Agree with SAB that knowing how to create your own Exceptions is a good idea.
You may find you create one Exception class for your current project, and make all your other Exceptions subclasses of that.
I think that, 99% of the time, all you need to do is to implement four overloaded constructors to match from Exception. If you extend an Exception class with only two constructors, you can try thisThat’s it. A whole class. Most of the time you don’t need to do anything else. If your superclass has four constructors, it is even easier because you can use super(...); on its own in all four constructors. I recommend you check carefully that I have spelt initCause right.
You may find the hardest part is choosing a superclass for your inheritance hierarchy. Remember that choice determines whether your Exceptions are checked or unchecked.