0
点赞
收藏
分享

微信扫一扫

return与try/catch,finally

雨鸣静声 2022-01-20 阅读 52

System.out.println();是运行后加进去的

void 可以和return一起用,此时return相当于break。而且return是可以省略的

package com.w3day3.test;

import java.io.FileNotFoundException;

/**
 *
 * throw: 作用在方法里面  如果抛出运行时期异常,调用者不要处理  并且不要配合throws使用
 *                      如果抛出编译时期异常,需要配合throws使用 ,调用者必须处理
 * throws: 作用在方法上  抛出异常   调用者必须处理  可以单独使用
 * 面试题
 *
 */

public class TextLoad {
    //  * 定义读取log.txt,如果文件不存在就抛给调用者,让调用者处理文件不存在的异常。


    public void loadFile(String fileName) throws FileNotFoundException {

        if(!"log.txt".equals(fileName)){
            // throw 编译时期异常,告诉调用报错,调用必须处理
            throw new FileNotFoundException("找不到对应的文件。");
        }


    }

    public void loadFile1(String fileName) throws FileNotFoundException {

        return;
    }




}

 

package com.w3day3.test;

import java.io.FileNotFoundException;

/**
 * @Title
 * @Author Eastlin
 * @Description:
 */
public class Return {
    public static void main(String[] args) {
        Return aReturn=new Return();
        aReturn.show();
    }
    public void show(){
        int i = 0;
        TextLoad textLoad = new TextLoad();
        //整体部分A代码块
        try {
            textLoad.loadFile("t22.txt");//log.txt
            System.out.println("1");
            return;//在try/catch中相当于break
        } catch (FileNotFoundException e) {
            e.printStackTrace(); //打印日志
            e.getMessage(); // 获取错误信息
            System.out.println("2");
            e.printStackTrace();
        }finally {//相当于static,局部的,这个也非必须出现在try/catch后
            System.out.println("3");
            System.out.println("我会执行吗?");
        }
        //A结束
        System.out.println("4");
        System.out.println("我会执行吗?.................");

    }
}
//    public void show(){
//        System.out.println("0");
//        return;
//        System.out.println();
//    }
//    public String show1(){
//        return "1";
//    }
//
//    public static void main(String[] args) {
//        Return aReturn=new Return();
//        aReturn.show();
//        aReturn.show1();
//    }
//}

 

举报

相关推荐

0 条评论