1) A custom exception class can be defined either within the class it is intended for or in a separate class.
Example of the former - ThrowingClass.java
:
public class ThrowingClass {
public static class ThrownInnerException extends Exception {
public ThrownInnerException() {};
}
public void throwingMethod() throws ThrownInnerException {
throw new ThrownInnerException();
}
}
Example of the latter - ThrownException.java
:
public class ThrownException extends Exception {
public ThrownException() {};
}
and ThrowingClass.java
:
public class ThrowingClass {
public void throwingMethod() throws ThrownException {
throw new ThrownException();
}
}
2) Multiple custom exception classes can be defined within a single class file. Each custom exception class does not require its own class file.
Example - MultiThrowingClass.java
:
public class MultiThrowingClass {
public static class ThrownExceptionTypeOne extends Exception {
public ThrownExceptionTypeOne() {};
}
public static class ThrownExceptionTypeTwo extends Exception {
public ThrownExceptionTypeTwo() {};
}
public void throwingMethodOne() throws ThrownExceptionTypeOne {
throw new ThrownExceptionTypeOne();
}
public void throwingMethodTwo() throws ThrownExceptionTypeTwo {
throw new ThrownExceptionTypeTwo();
}
}