0

ok, here's my problem.

I want to create my own custom exceptions such as 'UsernameAlreadyTakenException'. I can create a single class in a file which extends Exception. My problem is, I'd rather not have 3 - 5 different files for each 'subclass' that do almost nothing. I'd like to stick them all in the same file. Is this possible and if so how??

Trevor Tiernan
  • 392
  • 1
  • 3
  • 9
  • 1
    Just create those 3 - 5 separate files for each exception type. In Java programs, it's normal to have one class per file (and required for `public` classes). It's better to get over it than to try to do special tricks just because you want them in one file. – Jesper Apr 11 '14 at 21:10
  • Why don't you want 3-5 different files? – Mike B Apr 11 '14 at 21:11
  • 1
    I don't want multiple files, because it seems like a waste. Each class only consists of a constructor. – Trevor Tiernan Apr 11 '14 at 21:13

2 Answers2

2

You can do this by making a static sub class (though I don't necessarily recommend it). Here's an example:

package com.sandbox;

public class Sandbox {
    public static void main(String[] args) throws Exception2 {
        throw new Exception2();
    }

    public static class Exception1 extends Exception {

    }

    public static class Exception2 extends Exception {

    }

    public static class Exception3 extends Exception {

    }


}
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
2

The only restriction against placing multiple classes inside the same file when compiling Java is that only one top-level class in the file can be marked public. This is because public classes must be in a file with the same name, and you can't have multiple classes with the same name.

It's usually a considered a poor practice, and it doesn't guarantee your classes will have the correct protection level, but you can just leave off public when declaring your additional classes. This will give them default protection.

For a good discussion on what default protection means (and the other protection levels), just see this question.

So you could create the file UsernameAlreadyTakenException.java and put in it something like:

public class UsernameAlreadyTakenException extends Exception {
    ...
}
class MySecondException extends Exception {
    ...
}
...
class MyNthException extends Exception {
    ...
}

You could even name the file something else, but then you can't have the class UsernameAlreadyTakenException marked as public. But once again, it is frowned upon to do this. It's usually just better to have a new file for each distinct class.

Community
  • 1
  • 1
Sam
  • 1,176
  • 6
  • 19