简体   繁体   中英

How do I create n-number exceptions in the same class?

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??

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 {

    }


}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM