b站学习视频以及笔记-尚硅谷_Java零基础教程
自定义异常类
如何自定义一个异常类?
-
如何自定义异常类?
-
继承于现的异常结构:RuntimeException 、Exception
-
提供全局常量:serialVersionUID
-
提供重载的构造器
public class MyException extends Exception{ static final long serialVersionUID = -7034897193246939L; public MyException(){ } public MyException(String msg){ super(msg); } } public class StudentTest { public static void main(String[] args) { try { Student s = new Student(); s.regist(-1001); System.out.println(s); } catch (Exception e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } } class Student{ private int id; public void regist(int id) throws Exception { if(id > 0){ this.id = id; }else{ // System.out.println("您输入的数据非法!"); //手动抛出异常对象 // throw new RuntimeException("您输入的数据非法!"); // throw new Exception("您输入的数据非法!"); throw new MyException("不能输入负数"); //错误的 // throw new String("不能输入负数"); } } @Override public String toString() { return "Student [id=" + id + "]"; } }

//自定义异常类
public class EcDef extends Exception {
static final long serialVersionUID = -33875164229948L;
public EcDef() {
}
public EcDef(String msg) {
super(msg);
}
}
/*
* 编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算两数相除。
对数据类型不一致(NumberFormatException)、缺少命令行参数(ArrayIndexOutOfBoundsException、
除0(ArithmeticException)及输入负数(EcDef 自定义的异常)进行异常处理。
提示:
(1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
(2)在main()方法中使用异常处理语句进行异常处理。
(3)在程序中,自定义对应输入负数的异常类(EcDef)。
(4)运行时接受参数 java EcmDef 20 10 //args[0]=“20” args[1]=“10”
(5)Interger类的static方法parseInt(String s)将s转换成对应的int值。
如:int a=Interger.parseInt(“314”); //a=314;
*/
public class EcmDef {
public static void main(String[] args) {
try{
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int result = ecm(i,j);
System.out.println(result);
}catch(NumberFormatException e){
System.out.println("数据类型不一致");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("缺少命令行参数");
}catch(ArithmeticException e){
System.out.println("除0");
}catch(EcDef e){
System.out.println(e.getMessage());
}
}
public static int ecm(int i,int j) throws EcDef{
if(i < 0 || j < 0){
throw new EcDef("分子或分母为负数了!");
}
return i / j;
}
}

这篇博客介绍了如何在Java中自定义异常类,包括继承Exception类,设置serialVersionUID和构造器。通过StudentTest和EcmDef类的示例,展示了如何在代码中抛出和捕获自定义异常,以及处理常见的运行时异常、数组越界异常、算术异常。此外,还给出了一个计算两数相除的程序,强调了输入负数时的异常处理。
1111

被折叠的 条评论
为什么被折叠?



