T
T
Tagoryanin2021-08-30 06:33:01
Java
Tagoryanin, 2021-08-30 06:33:01

How to create your own exception class?

I'm trying to create a class with my own exceptions by type:

int num = x;
        if (num == 0) {
            throw new MyException("Это ноль!");
        } 

        if (num<10){
            System.out.println("Меньше 10");
        }
        else  {
            System.out.println("Больше");
        }

        class MyException extends Exception{

            }

The problem is that IDEA swears and asks to create the MyException class, despite the fact that it is below and whether there is something in it.
Questions:
1. How to connect them so that the exception is processed and the program ends with the appropriate message?
2. What is more correct to write in the class if you do not need to calculate anything, but you just need to check for invalid values ​​and terminate the program if they appear?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tagoryanin, 2021-08-30
@Tagoryanin

public class test10 {
    public static void main(String[] args) throws Exception {

        int num = x;
        try {
            if (num == 0) {
                throw new MyException();
            }
        }
        catch (MyException s){
            System.out.println("Exception: " + s.toString());
            return;
        }

        if (num<10){
            System.out.println("Меньше 10");
        }
        else  {
            System.out.println("Больше");
        }


    }
    static class MyException extends Exception{

        public String toString() {
            return "Недопустимое значение - ноль.";
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question