【Java】关于catch和throw 方法差异——Exception的一些总结

一、问题

最近,简单研究了下Exception的一些问题,现总结如下;

二、分析

首先,我想说的是,catch异常和throw异常;

throw是抛出异常,往哪里抛?往上层抛。上层是哪里?哪个调用我的这个方法,我就抛给谁;
catch是方法内抓取异常,然后处理;当然,处理的方法,也包含往上抛,或者说往外抛;

我们先来看一段代码:

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Auther
 * @title: TestException
 * @projectName generatorSqlmapCustom
 * @description: TODO
 * @date 27/03/201909:50
 */
public class TestException {

    @Test
    public void testTryCatch(){
        try {
            getRead();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("顶层:");
        }
    }


    public static void getRead() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = dateFormat.parse("2018-1a 3-01");
            System.out.println("date:"+date);
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("【解析异常】");
        }catch (Exception e) {
            System.out.println("【异常】");
            //throw new Exception();
        }
    }
}

1、这里,我们写了一个测试方法,一个静态方法;测试方法作为父方法,调用子静态方法;
我们看到,子静态方法解析日期格式时,可能会有【解析异常】(ParseExcetpion),所以,我们通过catch来抓取异常,并且,抓取异常是有顺序要求的,范围小的要写在前面(上面),越大的,写的越靠后,从上而下,一层层筛异常;因为Exception是所有异常的父类,他可以拦截所有的异常,如果把Exception作为catch的第一项,则后面具体的异常将无法匹配到;测试结果如下:

【解析异常】
java.text.ParseException: Unparseable date: "2018-1a 3-01"
	at java.text.DateFormat.parse(DateFormat.java:366)
	at TestException.getRead(TestException.java:33)
	at TestException.testTryCatch(TestException.java:22)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Process finished with exit code 0

2、接下来,我们把所有的异常都catch住,然后再抛出去,为什么不直接throw呢?其实可以直接抛的,这么做是为了打印下日志,让大家看的更清楚,子方法被那个catch抓住了;代码如下:

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Auther
 * @title: TestException
 * @projectName generatorSqlmapCustom
 * @description: TODO
 * @date 27/03/201909:50
 */
public class TestException {

    @Test
    public void testTryCatch(){
        try {
            getRead();
        }catch (ParseException e){
            e.printStackTrace();
            System.out.println("【顶层解析异常】");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("【顶层异常】");
        }
    }


    public static void getRead() throws Exception,ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = dateFormat.parse("2018-1a 3-01");
            System.out.println("date:"+date);
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("【解析异常】");
            throw new ParseException("解析异常",e.getErrorOffset());
        }catch (Exception e) {
            System.out.println("【异常】");
            throw new Exception();
        }
    }
}

console控制台输出信息:

【解析异常】
java.text.ParseException: Unparseable date: "2018-1a 3-01"
【顶层解析异常】

	at java.text.DateFormat.parse(DateFormat.java:366)
	at TestException.getRead(TestException.java:33)
	at TestException.testTryCatch(TestException.java:19)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
java.text.ParseException: 解析异常
	at TestException.getRead(TestException.java:38)
	at TestException.testTryCatch(TestException.java:19)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Process finished with exit code 0

我们发现,子方法中的【解析异常】被ParseException的catch抓取,然后抛出ParseException;父方法抓住了这个ParseException;

三、总结

1、catch异常有顺序的要求,异常应该从小到大顺序写;否则会报错;
2、throw 后面抛的异常没有顺序的要求;如果有匹配的小范围的具体异常,会自动抛出throw里的具体的异常,如果throw没有具体的小范围的异常,则会抛出Exception(如果有的话);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陶洲川

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值