I'm used to programming in C++, where you would declare multiple custom exceptions like so in a single class: c++Exceptions, and you would call those custom exceptions with throw new ExceptionEnumerationBeyondEnd().
How would I do this in Java?
From what I've learned in Java, one has to define each exception in it's own individual class. Is there anyway I can have an exceptions class that contains multiple custom exceptions as in c++, and just call a throw command when they get violated?
I plan on using it in a try catch block like this,
try {
if(...) throw new customException1();
else ...
} catch (customException1) {
} catch (customException2) {
} ...
I will try to give a few examples in Java as I am unsure from the picture and your statement:
What you precisely mean with the declare multiple custom exceptions in a single class.
Interface
In Java you can either define a
Interfaceand implement that and use it in typing like so:Then create a class that implements it.
And when you throw anything you can get away with catching only
CustomException.Base class
The other way you can go is to extend one of the built in Exception classes like
RuntimeExceptionor justExceptionitself.Then you can extend from that custom class and use it in typing as normal.
Then this works again like previously:
Inside the catch you catch them all in one go. If you need to do different logic on different catches you can do separate
catchblocks otherwise the other option you can do is:Non conventional
This I am putting here for completeness sake but it is not conventional. You could create one file in your project called
Exception.java. Inside you can define as many classes as you want and you can refer to them by importing them but it is not the idiomatic way to write Java.So inside
Exception.java:Hope this helps you out and continues you on your journey.