java中在catch中抛出自己定义的异常

要求是这样的;
有一个String字符串需要转型为int类型

Sting s;
Integer.parseInt(s);
我想在Integer.parseInt(s);周围try catch,并在catch中抛出自己的异常
意思是如果强转出错 则抛出自己定义的异常

这样做了 貌似每次异常都抛出? 我该怎么写???????或者怎么实现

通过throw抛出自定义异常

1、定义一个自定义异常类

public class CustomException extends Exception {    //或者继承任何标准异常类
    public CustomException()  {}                //用来创建无参数对象
    public CustomException(String message) {        //用来创建指定参数对象
        super(message);                             //调用超类构造器
    }
}

2、抛出异常

try{
//执行语句
}catch(Exception ex){
   throw new CustomException("自定义异常");//在catch中抛出自定义异常
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-07
首先,你的s没有给初始值,编译通不过
String s = null;
其次,
try {
Integer.parseInt(s);
} catch (Exception e) {
// TODO: handle exception
throw new Exception("自定义异常");
}本回答被网友采纳
第2个回答  2012-07-18
Integer.parseInt(String arg),这是JAVA API里已经定义好的。不能抛出自己的异常,除非你写个子类继承Integer,再复写这个parseInt方法。
第3个回答  2012-07-18
写一个自己的异常XXXException extends Exception;
然后在catch中写throw new XXXException(s);
第4个回答  2012-07-18
重写exception,内容自己定义,可输出stack信息,自己定义信息随意了。