在JAVA中,用户程序如何自定义异常?编程实现一个用户自定义异常
答案:3 悬赏:30 手机版
解决时间 2021-02-13 13:31
- 提问者网友:捧腹剧
- 2021-02-13 08:18
在JAVA中,用户程序如何自定义异常?编程实现一个用户自定义异常
最佳答案
- 五星知识达人网友:骨子里都是戏
- 2021-02-13 09:48
public class NewException extends Exception{
public NewException() {
super();
// TODO Auto-generated constructor stub
}
public NewException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public NewException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public NewException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
public class ExceptionTest {
public static void main(String[] args) throws NewException {
System.out.println("开始正常");
try {
String str = null;
str.length();//将抛出异常
System.out.println("结束正常");
} catch (Exception e) {
e.printStackTrace();
throw new NewException("str.length()出现异常", e);
} finally{
}
}
}
自己定义一个异常只需继承(extends)Exception这个类或者Throwable这个类,然后继承父类的构造器就可以了
全部回答
- 1楼网友:青尢
- 2021-02-13 11:47
我就简单点写了。写一个异常类,这个类跟我们平常的类没有什么区别,它需要继承Exception或Throwable或其子类。里面是一些构造器和方法。然后在程序里面调用,如:
//异常类 MyException
package day20120220;
public class MyException extends Exception{
public MyException(){
System.out.println("除数不能为0");
}
}
package day20120220;
//Main方法
public class Main {
public static void main(String[] args ) throws MyException {
int a=5;
int b=0;
if(b==0){
throw new MyException();
}else{
System.out.println(a/b);
}
}
}
//异常类 MyException
package day20120220;
public class MyException extends Exception{
public MyException(){
System.out.println("除数不能为0");
}
}
package day20120220;
//Main方法
public class Main {
public static void main(String[] args ) throws MyException {
int a=5;
int b=0;
if(b==0){
throw new MyException();
}else{
System.out.println(a/b);
}
}
}
- 2楼网友:举杯邀酒敬孤独
- 2021-02-13 10:57
public class FileCanNotWriteException extends Exception {
private static final long serialVersionUID = -4783225693686799018L;
public FileCanNotWriteException(){
super();
}
public FileCanNotWriteException(String msg){
super(msg);
}
public FileCanNotWriteException(String msg,Throwable cause){
super(msg,cause);
}
public FileCanNotWriteException(Throwable cause){
super(cause);
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯