218 异常处理之throws

218 异常处理之throws

虽然我们通过try…catch可以对异常进行处理,但是并不是所有的情况我们都有权限进行异常的处理。

也就是说,有些时候可能出现的异常是我们处理不了的,这时候该怎么办?

针对这种情况,Java提供了throws处理方案

【throws格式】

throws 异常名;

注意/这个格式跟在方法名后面,例如public static void method throws ParseException(){…}

> 抛出异常不是实际处理,只是把异常抛出去了,抛出的意义在于可以交给调用者去处理

--------------------------------------------------------------

(module)myException

(package)it04e218

class)ExceptionDemo

--------------------------------------------------------------

package it04e218;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

public class ExceptionDemo {

    public static void main(String[] args) {

        System.out.println("begin");

        method();

        method2();

        System.out.println("end");

    }

    public static void method () throws ArrayIndexOutOfBoundsException{

        int[] arr = {1,2,3};

        System.out.println("218/arr[3]:\n"+arr[1]);

    }

    

    //编译时异常,例如parse

    public static void method2() {

        try{

            String s = "2021-09-23";

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Date d = sdf.parse(s);

            System.out.println("d:\n"+d);

        }catch(ParseException p){

            System.out.println("?");

        }

    }

}

//OUTPUT:

//        begin

//        218/arr[3]:

//        2

//        d:

//        Thu Sep 23 00:00:00 CST 2021

//        end

> 怎么打出成对的单引号?——中文状态下,单击引号键即可,别的什么也不要按

Guess you like

Origin blog.csdn.net/m0_63673788/article/details/121508222