Custom Exceptions Class Naming in Java
-
21-07-2021 - |
문제
I am trying to create a custom exception class but having trouble naming. Here's what I have so far:
public class MyException extends Exception {
public MyException() {
}
}
Now, I want an exception that is not called MyException
. Can I use:
public void EmptyException() {
}
Thank you for your help.
해결책
yes ofcourse, just do the same thing again :) create a new class called EmptyException
in same class:
public class EmptyException extends Exception {
public EmptyException() {
}
public class InnerException extends Exception { //Inner class
public InnerException() {
}
}
}
다른 팁
Prefer creating one exception per file:
Within MyException.java:
public class MyException extends Exception {
//useless to define here the default constructor
}
Within EmptyException.java
public class EmptyException extends Exception {
//useless to define here the default constructor
}
In this case, using inner-classes = code smell.
If both exceptions are really linked together, prefer inheritance over inner-classing:
public class EmptyException extends MyException {
//useless to define here the default constructor since parent's constructor is zero-arg one.
}
제휴하지 않습니다 StackOverflow