How to create runtime 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 id type of validation . If id is greater then expected then it generate
exception . How check the code .
package Exceptions;
public class Customer{
private String name ;
private int id;
public Customer() {}
public Customer(int id2) {
// TODO Auto-generated constructor stub
System.out.println(" Id is :"+id);
}
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;
}
}
package Exceptions;
public class NameNotFoundException extends Exception{
/**
* @author Mukesh
*/
private static final long serialVersionUID = 1L;
public NameNotFoundException(String message) {
System.out.print(message);
}
}
package Exceptions;
public class CreateOwnExceptions {
public Customer findById(int id) throws NameNotFoundException {
if ( id >= 10000) {
throw new NameNotFoundException(" Invaild customer id");
}
return new Customer( id);
}
public static void main(String[] args) {
CreateOwnExceptions obj = new CreateOwnExceptions();
try {
obj.findById(20000);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
Program output ..
Invaild customer idExceptions.NameNotFoundException
at Exceptions.CreateOwnExceptions.findById(CreateOwnExceptions.java:17)
at Exceptions.CreateOwnExceptions.main(CreateOwnExceptions.java:33)
How to create runtime exception
Reviewed by Mukesh Jha
on
1:58 AM
Rating:
No comments:
Add your comment