Following are the steps to create custom exception.
(1) create a custom exception class in Java;
(2) throw our custom Java exception;
(3) catch our custom exception; and
(4) look at the output from our custom exception when we print a stack trace.
To create a custom exception class, all you have to do is extend the Java Exception class, and create a simple constructor:
A method to throw our custom Java exception
here's a small example class with a method named getUser that will throw our custom exception (CustomException) if the method is given the value of zero as a parameter.
To test our custom Java exception. In our main method, we'll create a new instance of our User class, then call the getUser method with the value of zero, which makes that method throw our custom Java exception:
(1) create a custom exception class in Java;
(2) throw our custom Java exception;
(3) catch our custom exception; and
(4) look at the output from our custom exception when we print a stack trace.
To create a custom exception class, all you have to do is extend the Java Exception class, and create a simple constructor:
/**
* My custom exception class.
*/
class CustomException extends Exception
{
public CustomException(String message)
{
super(message);
}
}
A method to throw our custom Java exception
here's a small example class with a method named getUser that will throw our custom exception (CustomException) if the method is given the value of zero as a parameter.
/**
* Our test class to demonstrate our custom exception.
*/
class User
{
public String getUser(int i) throws CustomException
{
if (i == 0)
{
// throw our custom exception
throw new CustomException("zero ...");
}
else
{
return "user";
}
}
}
To test our custom Java exception. In our main method, we'll create a new instance of our User class, then call the getUser method with the value of zero, which makes that method throw our custom Java exception:
/**
* A class to test (throw) the custom exception we've created.
*
*/
public class CustomExceptionExample
{
public static void main(String[] args)
{
// create a new User
User user= new User();
try
{
// intentionally throw our custom exception by
// calling getUser with a zero
String userStr= user.getUser(0);
}
catch (CustomException e)
{
// print the stack trace
e.printStackTrace();
}
}
}
In the try block duplicate string reference
ReplyDeleteHi Amar,
ReplyDeleteThanks for correction. I will update post.