try-catch、throw、throws的作用

try-catch

try-catch捕获try代码块的异常,并在catch中执行,try外面的代码块,会继续执行

如下所示

package newT.exception;

import java.util.Scanner;

/**
 * try-catch处理可能会出现异常情况,若发生在try中发现异常,在catch处理以后,try-catch外层的语句还能继续执行
 */
public class TryCatch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("---------学生信息录入---------------");
        String name = ""; // 获取学生姓名
        int age = 0; // 获取学生年龄
        String sex = ""; // 获取学生性别
        try {
            System.out.println("请输入学生姓名:");
            name = scanner.next();
            System.out.println("请输入学生年龄:");
            age = scanner.nextInt();
            System.out.println("请输入学生性别:");
            sex = scanner.next();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("输入有误!");
        }
        System.out.println("姓名:" + name);
        System.out.println("年龄:" + age);
        System.out.println("性别" + sex);
    }
}

throw 

throw捕获异常后不会执行try代码块以外的代码

package newT.exception;

public class Throw {
    public static void main(String[] args) {
        try {
            throwMethods("2.123za");
            System.out.println("不会执行");
        } catch (Exception e) {
            System.out.println("交给外层处理");
            e.printStackTrace();
        }
    }

    public static void throwMethods(String data) throws Exception {
        try {
            Double.parseDouble(data);
        } catch (NumberFormatException e) {
            throw new Exception("发送异常");
        }
        System.out.println("throw捕获异常后不会执行后面的代码");
    }
}

throws

throws捕获异常后不会执行try代码块以外的代码

package newT.exception;

import java.io.File;
import java.io.FileInputStream;

/**
 * throws 向外抛异常 抛给调用者
 * 如果没有try-catch则一层一层往上抛
 * 有try-catch则捕获抛出的异常对其进行处理
 */
public class Throws {
    public static void main(String[] args) throws Exception {
        try {
            //调用者
            throwException();
        } catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    public static void throwException() throws Exception{
        File file = new File("404");
        FileInputStream fileInputStream = new FileInputStream(file);
        System.out.println("代码不会继续执行");
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值