在JAVA中,用户程序如何自定义异常?编程实现一个用户自定义异常
发布网友
发布时间:2022-05-14 20:01
我来回答
共3个回答
热心网友
时间:2023-10-27 12:09
/**
* class名:NewException
* class说明:在JAVA中,用户程序如何自定义异常?编程实现一个用户自定义异常
* @author Jr
*
*/
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
}
}
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
/**
* class名:ExceptionTest
* class说明:制造一个异常,来测试NewException类
* @author Jr
*
*/
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这个类,然后继承父类的构造器就可以了
热心网友
时间:2023-10-27 12:09
我就简单点写了。写一个异常类,这个类跟我们平常的类没有什么区别,它需要继承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);
}
}
}
热心网友
时间:2023-10-27 12:10
/**
* @description 文件不可写异常
* @author Guanweili
*
*/
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);
}
}