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
  • 相关阅读:
    ASP.NET MVC Razor 视图引擎
    Asp.net MVC3 Razor语法小记
    @RenderPage用法
    余数算法
    Linux命令行下运行java.class文件
    Java学习---9.GUI编程
    Java学习---8.线程同步
    Java学习---7.多线程
    Java学习---6.常用的容器,流
    Java学习---5.数组
  • 原文地址:https://www.cnblogs.com/pyleu1028/p/10332779.html
Copyright © 2011-2022 走看看