Java program to create custom exception
Here's a Java program to create a custom exception:
refer toi:giftidea.compublic class MyCustomException extends Exception { public MyCustomException(String message) { super(message); } }
This program creates a new class called MyCustomException
which extends the Exception
class. We can add additional fields and methods to this class if we want, but for this example, we are just creating a simple custom exception.
In this example, we have added a constructor that takes a String
message as a parameter. We are calling the super()
method in this constructor to set the message of the exception.
Now we can use this custom exception in other parts of our code. Here's an example of how we can throw this exception:
public class Main { public static void main(String[] args) { try { // Throw the custom exception with a custom message throw new MyCustomException("This is my custom exception message."); } catch (MyCustomException e) { System.out.println(e.getMessage()); } } }
In this example, we are throwing the MyCustomException
with a custom message. We are then catching the exception using a catch
block and printing the message to the console.
This is just a simple example of how to create and use a custom exception in Java. You can customize the MyCustomException
class to add additional fields and methods to meet your specific needs.