How to create custom exception in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Arrays;
 
class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}
 
public class MyClass {
 
    ArrayList<String> al = new ArrayList<>(Arrays.asList("Java", "C++", "Python", "C"));
 
    public void checkExists(String s) throws CustomException {
        if (al.contains(s)) {
          throw new CustomException(s + " already exists");
        }
        else {
          al.add(s);
        }
    }
    public static void main(String args[]) {
        MyClass obj = new MyClass();
 
        try {
            obj.checkExists("Java");
            obj.checkExists("PHP");
        }
     
        catch(CustomException e) {
            System.out.println(e);
        }
    }
}
 
 
 
 
/*
run:
 
CustomException: Java already exists
 
*/

 



answered Jan 19, 2022 by avibootz
...