How to Create your own Exception
Java exception are two
types
1. Runtime Exceptions
or Unchecked Exception
2. Compile time Exception
or Checked Exception
This example
explain how to create own own unchecked exception .
This code
verifies the
customer name type of validation . If name is
blank then it generate
exception .
How check the code .
class Customer{
private String
name ;
private
int id;
public Customer(String name2)
{
System.out.println("Welcome
:"+name2);
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String
getName() {
return name;
}
public void setName(String name)
{
this.name = name;
}
A class need to create class of
desire exception type
package Exceptions;
public class NameNotFoundException extends Exception{
/**
* @author Mukesh
*/
private static final long serialVersionUID = 1L;
public NameNotFoundException(String message) {
System.out.print(message);
}
}
public class CreateOwnExceptions {
public Customer findByName(String name) throws NameNotFoundException {
if ("".equals(name)) {
throw new NameNotFoundException("Name is
empty!");
}
return new Customer(name);
}
public static void main(String[] args) {
CreateOwnExceptions obj = new CreateOwnExceptions();
try {
Customer cusm = obj.findByName("Mukesh");
Customer cus = obj.findByName("");
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
When you run this
code this out put you will get.
Welcome :Mukesh
Name is empty!Exceptions.NameNotFoundException
at
Exceptions.CreateOwnExceptions.findByName(CreateOwnExceptions.java:41)
at Exceptions.CreateOwnExceptions.main(CreateOwnExceptions.java:57)
How to Create your own Exception
Reviewed by Mukesh Jha
on
11:23 AM
Rating:
No comments:
Add your comment