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
  • 相关阅读:
    js获取 DOM 里所有图片(包括背景和iframe)
    php 和 js互相调用
    mac 权限
    node 启动命令
    three.js THREE.MeshLine.js 回显3D路径
    Vue2, Vue3 开发单一html页面区别
    前端布局,相关链接
    jq国际化jquery.i18n.properties使用
    资料
    其它工具
  • 原文地址:https://www.cnblogs.com/pyleu1028/p/10332779.html
Copyright © 2011-2022 走看看