通过throw抛出自定义异常
1、定义一个自定义异常类
public class CustomException extends Exception { //或者继承任何标准异常类
public CustomException() {} //用来创建无参数对象
public CustomException(String message) { //用来创建指定参数对象
super(message); //调用超类构造器
}
}
2、抛出异常
try{
//执行语句
}catch(Exception ex){
throw new CustomException("自定义异常");//在catch中抛出自定义异常
}
首先,你的s没有给初始值,编译通不过
String s = null;
其次,
try {
Integer.parseInt(s);
} catch (Exception e) {
// TODO: handle exception
throw new Exception("自定义异常");
}
Integer.parseInt(String arg),这是JAVA API里已经定义好的。不能抛出自己的异常,除非你写个子类继承Integer,再复写这个parseInt方法。
写一个自己的异常XXXException extends Exception;
然后在catch中写throw new XXXException(s);
重写exception,内容自己定义,可输出stack信息,自己定义信息随意了。