Learn how to Making Custom (User Defined) Exceptions.
Making Custom (User Defined) Exceptions
<<<<<<< making_custom.shtmlMaking Custom (User Define Exceptions)
So far you would have been known, how to be handled the exceptions in java =======
So far you would have been known, how to be handled the exceptions in java >>>>>>> 1.3 that are thrown by the Java API but sometimes you may occasionally need to throw your own exception i.e. if you encounter a situation where none of those exception describe your exception accurately or if you can't find the appropriate exception in the Java API, you can code a class that defines an exception that is more appropriate and that mechanism of handling exception is called Custom or User Defined Exception.
In Java API all exception classes have two type of constructor. First is called default constructor that doesn't accept any arguments. Another constructor accepts a string argument that provides the additional information about the exception. So in that way the Custom exception behaves like the rest of the exception classes in Java API.
There are two primary use cases for a custom exception.
- your code can simply throw the custom exception when something goes wrong.
- You can wrap an exception that provides extra information by adding your own message.
The code of a Custom exception:
public class ExceptionClassName extends Exception { public ExceptionClassName(){ } public ExceptionClassName(StringMessage) { super(message); } } |
Lets see an example that has the implementation of User Define Exception:
import java.io.*; import java.util.*;
class MyException extends Exception
nm=s; String temp=""; try
if(!temp.equals(str)) |
Output of the program:
C:\Roseindia\>javac
ExcepDemo.java
C:\Roseindia\>java ExcepDemo Enter the your name nisha you are not permitted to enter inside nisha C:\Roseindia\>java ExcepDemo Enter the your name amit Welcome to Rose India 0 |
In this example we have created own exception class as MyException that throws an exception and a function with argument as getMessage that shows an exception message, if the user tries to enter the another name which doesn't match with a particular predefined name. After throwing exception the control will be transferred in the catch block to handle the exception where the function is invoked to display the message included in that function.
1