1.定义一个方法,当这个方法出错时,抛出一个自定义异常。
2.用 try catch 捕捉该方法抛出的异常并处理
3. 定义一个方法,调用并转抛异常
4. 用 try catch 语句捕捉异常,并输出异常的抛出过程
请问这个如何实现,求大神附上代码,谢谢
根据你的描述,编写测试代码如下:
import java.util.ArrayList;
import java.util.List;
public class ExceptionTest {
/**
* 判断某个列表中,某个位置处的值是否是指定的字符串
* 可能抛出两种异常
* @param value
* @param list
* @param index
* @return
*/
public static boolean isTargetInCertainIndex(String value,List<String> list,int index)
throws IllegalArgumentException,IndexOutOfBoundsException {
if(value==null||list==null){
throw new IllegalArgumentException("date is null");
}
if(index>list.size()){
throw new IndexOutOfBoundsException("index is out of bounds");
}
boolean flag = false;
String data = list.get(index);
return value.equals(data);
}
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
list.add("I");
boolean flag = false;
//没有异常的测试
try {
flag = isTargetInCertainIndex("hello",list,0);
System.out.println("flag:"+flag);
} catch (Exception e) {
System.out.println(e.getMessage());
}
//一种异常的情况
try {
flag = isTargetInCertainIndex(null,list,0);
System.out.println("flag:"+flag);
} catch (Exception e) {
System.out.println(e.getMessage());
}
//另一种异常的情况
try {
flag = isTargetInCertainIndex("hello",list,4);
System.out.println("flag:"+flag);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
仅供参考:
public class tmp
{
public static int division(int a,int b)
{
return a / b;
}
public static void main(String[] args)
{
try
{
tmp.division(4,0);
}
catch(Exception e)
{
System.out.println("Exception Class");
}
}
}
1.自定义的异常一定要大于等于截获的异常
2.自定义异常通常都集成RuntimeException这个类
3.在方法生命处thows 自定义的异常或者在try catch语句中throw new 自定义的异常