1

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.

2 Answers2

3

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.
}
Mik378
  • 21,881
  • 15
  • 82
  • 180
1

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() {
               }

          }
    }
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • 2
    @isal A custom exception is simply a class which extends `Exception`. All the rules that apply to classes in general when it comes to location in a file apply to custom exceptions just as well. As an alternative to the inner class in this answer, you can have a non-public top-level exception class. – Code-Apprentice Oct 30 '12 at 23:53
  • 2
    Although possible, why would you want to create an exception as an inner class of another exception? Looks like a code smell to me. – assylias Oct 30 '12 at 23:54
  • @assylias I have about 4 exceptions that are reused through out the program. I just felt having 4 different classes with one method in each would be mundane. Maybe I'm wrong, but that was my thinking. –  Oct 31 '12 at 00:02
  • Yup. Classes are cheap; if you're using them throughout the program, then making them their own classes is totally the way to go. – Louis Wasserman Oct 31 '12 at 04:34