Search code examples
javaexceptioninheritancecustom-exceptions

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


Solution

  • 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 {
    
        }
    
    
    }