异常和异常的处理

本文详细介绍了Java中的异常处理机制,包括try-catch-finally结构,throw和throws关键字的区别,以及如何在方法中处理和声明异常。通过实例演示了如何在程序中使用这些概念。
摘要由CSDN通过智能技术生成

java的异常处理是通过5个关键字来实现:try,catch,finally,throw,throws。

try,catch,finally

//public class test {
//    public static void main(String[] args) {
//        try {
//            int num1 = 12;
//            int num2 = 0;
//            System.out.println("两个数的商为:" + num1 / num2);
//        }catch(Exception ex){
//            System.out.println("你的程序出错了");
//        }
//        System.out.println("");
//    }
//}
public class test {
    public static void main(String[] args) {
        try {
            int num1 = 12;
            int num2 = 0;
            System.out.println("两个数的商为:" + num1 / num2);
        }catch(InputMismatchException ex){
            System.out.println("你的程序出错了");
        }finally {
            System.out.println("继续执行文件");
        }
    }
}

throw\throws

抛出异常

throw和throws区别:

(1)位置不同:
throw:方法内部
throws:方法的签名处,方法的声明处

(2)内容不同:
throw+异常对象throws+异常的类型

(3)作用不同:
throw:异常出现的源头,制造异常。
throws: 在方法的声明处,告诉方法的调用者,这个方法中可能会出现我声明的这些异常。然后调用者对这个异常进行处理:要么自己处理要么再继续向外抛出异常。

public class test1 {
    public static void main(String[] args) {
        devide();
    }
    //提取一个方法,两个数相除
    public static void devide() throws Exception {
        int num1 = 12;
        int num2 = 3;
        if(num2 == 0){
            //人为制造异常
//            try {
//                throw new Exception();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            System.out.println("try-catch处理异常");
            throw new Exception();//抛出异常
        }
        else{
            System.out.println("两个数的商是:" + num1/num2);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值