异常(Exception)

1.1 什么是异常

       异常情况是指程序在运行时,与我们一厢情愿所设想的不一设,而导致程序可能会出错的情况

1.2 异常体系

 *Throwable类是Java语言中所有错误和异常的父类  

       ——异常(Exception): 程序运行过程中,可以依靠程序本身解决的问题。

 1.2.1 检查异常

        1、ClassNotFoundException:类无法加载异常

        2、FileNotFoundException: 文件无法加载异常

        3、IOException: IO异常


1.2.2 运行时异常

        1、InputMismatchException: 输入类型不匹配

        2、ArithmeticException: 算数异常

        3、NullPointerException:空指针异常

        4、ArrayIndexOutOfBoundsException:数组下标越界异常

        5、ClassCastException:类转换异常

        6、NumberFormatException: 数字格式化异常

 1.2.3 错误(Error)

错误是指程序运行过程中,依靠程序本身不可以解决的严重性问题

1.3 异常处理

try:  捕获异常
    ....
 catch :  处理对应的异常  

例如以下代码:

import java.util.Scanner;

public class ArithmeticException {

    public static void main(String[] args){
        try{
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入被除数:");
            int a = sc.nextInt();
            System.out.println("请输入除数:");
            int b = sc.nextInt();
            System.out.println("结果为:" + a / b);
        }catch (InputMismatchException e){
            System.out.println("除数不能是零");
        }
    }
}

注意: catch 可以运行有多个,但是从子到父的顺序编写。

finally: 无论是否有异常,都必定执行的语句。

注意: 通常用来释放一些内存资源 ,当 try 语句中有return时,先执行finally,再执行return。

throws表示用来声明方法可能会抛出那些异常: 语法是:  throws 异常类型1,异常类型2…

throw表示抛出异常,语法是: throw new 异常类型([异常信息]);例如:

public static void sanjiao(int a,int b,int c)throws Exception{
        if(a+b-c > 0 && a+c-b > 0 && b+c-a > 0) {
            System.out.println("三角形的边长分别为:"+a+","+b+","+c);
            return;
        }
        throw new AException(a+","+b+","+c+"不能构成三角形");
    }
}
public class AException extends Exception {
    private String message;

    public String getMessage() {
        return message;
    }

    public AException(){

    }
    public AException(String message) {
        this.message = message;
    }
}


   
 
   



         
    
   
         



          
          
          
          
          

     

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值