![]() |
![]() |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Introduction of Errors | |
Java Exceptions | |
Java Try Block | |
Java Catch Block | |
Java Finally Block | |
Java Throw Keyword | |
Java Throws Keyword | |
Java Builtin Exceptions | |
User Defined Exceptions |
Java Multithreading | |
Creating a Thread | |
Thread Life Cycle | |
Thread Exceptions | |
Thread Synchronization |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
Java allows us to make our own exceptions called as User Defined Exceptions.
Java’s built-in exceptions handle most common errors,you will probably want to create your own exception types to handle situations specific to your applications.
Steps
Program for throwing an IncorrectPasswordException when user enters a wrong password.
import java.lang.Exception //optinal class IncorrectPasswordException extends Exception // user defined class { public IncorrectPasswordException(String msg) { super(msg); } } public class Test { public static void main(String[] args) { int pass=1122; try { if(pass != 1234) throw new IncorrectPasswordException("Wrong password entered"); else System.out.println("Welcome user."); } catch(IncorrectPasswordException e) { System.out.println("Error! "+e.getMessage()); } } }
Output
In above example, We have created IncorrectPasswordException class which is having Exception as Parent class. We have passed the msg String in its parameterized constructor for initialization of String. In class Test we have written try block which checks for the exception based on written condition.
If condition is true then compiler will throw an IncorrectPasswordException by passing message and call the matching catch block.
We can throw any exception like these.
Sr.no | Exception | Application Type |
---|---|---|
1. | IncorrectPinException | ATM Application |
2. | ProcessExecutionFailedException | System Application |
3. | BatteryLowException | Mobile Application |
4. | TransactionFailedException | Banking/Online Application |
5. | EmptyTankException | Water Purifier Application |