Java自定义异常的例子
在Java中,有两种类型的异常:检查和未检查异常.
检查:
java.lang.Exception
,对于可恢复的条件,异常捕获异常,编译错误。未检查
:java.lang.RuntimeException
,对于不可恢复的条件,如编程错误,不需要捕捉,运行时错误。一. 自定义检查异常
IOException, FileNotFoundException
1.如果客户端能够从异常中恢复,则将其作为一个检查的异常。要创建一个自定义的检查异常,扩展java.lang.exception
package com.mkyong.examples.exception;
public class NameNotFoundException extends Exception {
public NameNotFoundException(String message) {
super(message);
}
}
2.对于检查过的异常,您需要尝试捕获异常。
CustomerService.java
package com.mkyong.examples;
import com.mkyong.examples.exception.NameNotFoundException;
public class CustomerService {
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) {
CustomerService obj = new CustomerService();
try {
Customer cus = obj.findByName("");
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
二. 自定义未经检查的异常
注意
一些流行的无节制的例外:NullPointerException,IndexOutOfBoundsException IllegalArgumentException
1 如果客户端无法从异常中恢复,则将其作为一个未检查的异常。要创建一个自定义不例外,java.lang.RuntimeException延伸
ListTooLargeException.java
package com.mkyong.examples.exception;
public class ListTooLargeException extends RuntimeException{
public ListTooLargeException(String message) {
super(message);
}
}
2.对于未检查异常,尝试捕获异常是可选的。
package com.mkyong.examples;
import com.mkyong.examples.exception.ListTooLargeException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CustomerService {
public void analyze(List<String> data) {
if (data.size() > 50) {
//runtime exception
throw new ListTooLargeException("List can't exceed 50 items!");
}
//...
}
public static void main(String[] args) {
CustomerService obj = new CustomerService();
//create 100 size
List<String> data = new ArrayList<>(Collections.nCopies(100, "mkyong"));
obj.analyze(data);
}
}
JAVA/208.html">http://www.itemperor.com/a/JAVA/208.html
原文链接:http://www.jxszl.com/biancheng/JAVA/446560.html