What We Are Learn On This Post
What and How you Call a Custom Exception?
In Post, we are getting the details. but before going to custom exception firstly we have to know what is an exception?
The simple word I can say that exceptions are events. which occurs during the execution of a program and that disrupts the normal flow of a program. Here are some examples of exceptions
- Arithmetic Exception
- ArrayIndexOutOfBoundException
- ClassNotFoundException
- FileNotFoundException
- NullPointerException
- NumberFormatException
What Is a Custom Exception?
Java Provides a facility to create an exception as per their needs. so the exception is created by the users that are called a custom exception.
package co.java.exception; @SuppressWarnings("serial") public class MyException extends Exception { //not compulsory public MyException() { super(); System.out.println("MyException"); } public String getFaultMessage() { return "U r not an adult ...."; } } </pre> <pre class="lang:default decode:true" title="Call Custom_Exception">package co.java.exception; import java.util.Scanner; public class CallCustomException { @SuppressWarnings("resource") public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter age: "); int age = s.nextInt(); try { if(age < 18) { throw new MyException(); } } catch(MyException e) { System.out.println(e.getFaultMessage()); } finally { System.out.println("finally"); } } }
Explanation:
Leave a Reply