Пользовательское настраиваемое исключение в Java

Опубликовано: 15 Февраля, 2022

Java предоставляет нам возможность создавать собственные исключения, которые в основном являются производными классами Exception. Например, MyException в приведенном ниже коде расширяет класс Exception.

We pass the string to the constructor of the super class- Exception which is obtained using “getMessage()” function on the object created.

// A Class that represents use-defined expception
class MyException extends Exception
{
    public MyException(String s)
    {
        // Call constructor of parent Exception
        super(s);
    }
}
  
// A Class that uses above MyException
public class Main
{
    // Driver Program
    public static void main(String args[])
    {
        try
        {
            // Throw an object of user defined exception
            throw new MyException("GeeksGeeks");
        }
        catch (MyException ex)
        {
            System.out.println("Caught");
  
            // Print the message from MyException object
            System.out.println(ex.getMessage());
        }
    }
}

Выход:

Пойманный
Гики

In the above code, constructor of MyException requires a string as its argument. The string is passed to parent class Exception’s constructor using super(). The constructor of Exception class can also be called without a parameter and call to super is not mandatory.

// A Class that represents use-defined expception
class MyException extends Exception
{
  
}
  
// A Class that uses above MyException
public class setText
{
    // Driver Program
    public static void main(String args[])
    {
        try
        {
            // Throw an object of user defined exception
            throw new MyException();
        }
        catch (MyException ex)
        {
            System.out.println("Caught");
            System.out.println(ex.getMessage());
        }
    }
}

Выход:

Caught
null

Эта статья предоставлена Пранджалом Матхуром . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью и отправить ее по электронной почте на deposit@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .