zoukankan      html  css  js  c++  java
  • [Java] 例外處裡 try/catch & throws

    public class CheckException {
        public static void main(String[] args) {
            
            File file = new File("xxxx");
            FileInputStream fis = new FileInputStream(file);

    因為沒有檔案,會出現FileNotFoundException

    解決方法如下

    1. 設立例外處裡  try/catch

    public class CheckException {
        public static void main(String[] args) {
            
            File file = new File("xxxx");
            try {
                FileInputStream fis = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

    2.使用throws(可丟多個),將指定錯誤出現的時候,將程序往外丟回給呼叫者處裡(可多層外拋)

    public static void main(String[] args) throws FileNotFoundException{

    也可指定父類別(囊擴範圍較大)的exception,將多種錯誤一同處理。

    public static void main(String[] args) throws IOException{

    可於內部主動設計throw,分設多種Eexception發生時的狀況外丟或throws

    File file2 = new File("CCCC");
      if (!file.exists()) {
          throw new FileNotFoundException("找不到檔案");
        //FileNotFoundException exception = new FileNotFoundException("找不到檔案");
        //throw exception
  • 相关阅读:
    10.用户管理
    9.更新系统时间
    8.标准输入输出重定向
    7.文件压缩与find命令
    6.Linux文件的详细属性
    5.Linux基础命令
    4.Linux目录结构
    3.磁盘光驱挂载
    2.xshell连接
    javascript中的location的用法
  • 原文地址:https://www.cnblogs.com/pyleu1028/p/10332779.html
Copyright © 2011-2022 走看看