Posted On: Feb 22, 2018
A custom exception is also known as a user-defined exception are derived classes of Java Exception classes. In order to create your Custom exception in Java following point must be taken care of.
Custom exception example in Java
class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } } class CustomExceptionTest{ static void validate(int age)throws InvalidAgeException{ if(age<18) throw new InvalidAgeException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ try{ validate(13); }catch(Exception m){System.out.println("Exception occured: "+m);} System.out.println("rest of the code..."); } }
Above is an example of a custom exception in Java that checks the age of voter. If age is less than 18 years than it throws an InvalidAgeException.
Never Miss an Articles from us.
There are basically four types of storage classes in Java:Automatic storage class: When a variable that is used in the coding is defined within a function and that also with the auto specifier the...
A JAVA program to generate Fibonacci series is as follows: import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { int n, a = 0, b = 0, c = ...
Garbage collection is the process of automatically managing memory in java. It is helpful to finds the unused objects that are no longer used by the program and deletes or remove them to free up the m...