java复习----异常类/泛型

Java提供异常类Exception(大写及其子类来描述程序运行时出现的各种异常
哈哈哈
ArithmeticException —— 整数被0除 int i=12/0;
NullPointerException —— 试图访问null引用的属性或方法
Date d=null;
System.out.println(d.toString());
NegativeArraySizeException —— 数组下标是负数
ArrayIndexOutofBoundsException —— 数组下标越界
ClassNotFoundException —— 请求的类未找到
IOException —— 读写文件错误
FileNotFoundException ——不能找到文件

java属于退出模型 —— 处理完异常,不返回正常执行部分
例子:
本例中try内部可以输出,try内部2无法输出,代码结束可以输出

ublic class excaept {
    public static void main(String[] args) {
   try{
       int a=2;
       System.out.println("try内部1");
       int b;
       b=a/0;
       System.out.println("try内部2");
   }
   catch (Exception a)
   {
       System.out.println("有异常");
   }
        System.out.println("代码结束");
    }
}

例子:
本例中只有第二个catch捕获异常

try{
       int a=2;
       System.out.println("try内部1");
       int b;
       b=a/0;
       System.out.println("try内部2");
   }
   catch (NegativeArraySizeException a)
   {
       System.out.println("有其他异常");
   }
   catch (ArithmeticException a)
   {
       System.out.println("有整数除0异常");
   }

子异常类的catch必须在前,父异常类的catch在后
若颠倒了,编译器会报错

finally块

拼写
确保在出现异常时所有清除工作都将得到处理
与try-catch块一起使用
无论是否出现异常,finally块都将运行

throw

原理:catch不知道 怎么处理这个异常,交给上一级(java自带jvm)处理
结果:控制台报对应的错
throws用在psvm

public static void main(String[] args) throws ArithmeticException

throw用在catch内,throw+e

catch (ArithmeticException a)
   {
       System.out.println("有整数除0异常");
       throw a;
   }
自定义异常类

重新完整写一遍
注意:
1.System.out.println(e.getMessage());//
2 主函数必须有try catch
3.throws 在第二个 类而不能是测试类,因为在第二个类 中抛出交给测试类处理,如果在测试类抛出就给编辑器了,而编辑器没有这个自定的异常

class MyException extends Exception{
    String message;
    MyException(int n){
       message=n+"不是正数";
    }
    public String getMessage(){
       return message;
    }
}
class A{
    public void f(int n) throws MyException{
        if(n<0){
          MyException ex=new MyException(n);
          throw(ex);                          //抛出异常,结束方法f的执行
        }
        double number=Math.sqrt(n);
        System.out.println(n+"的平方根:"+number);
    }
}
public class Example5_19{
    public static void main(String args[]){
        A a=new A();
        try{ 
             a.f(28);
             a.f(-8);
        }
        catch(MyException e){
             System.out.println(e.getMessage());//
        }
    }
}

泛型

可以使用“class 名称<泛型列表>”声明一个类,为了和普通的类有所区别,这样声明的类称作泛型类,如:
class A
其中A是泛型类的名称,E是其中的泛型,也就是说我们并没有指定E是何种类型的数据,它可以是任何对象或或接口,但不能是基本类型数据
泛型类声明时,“泛型列表”给出的泛型可以作为类的成员变量的类型、方法的类型以及局部变量的类型。
例如:
void makeChorus(E person,F yueqi){
yueqi.toString();
person.toString();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值