zoukankan      html  css  js  c++  java
  • 捕获异常的两种方式Exception

    1、抛出异常:让调用此方法的代码去管

    public static void GetFile() throws Exception{}

    package com.throwable;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.InputStreamReader;
    
    public class ExcetionDemo {
    
    	/**
    	 * @param args
    	 * @throws Exception 
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
               
    		try {
    			GetFile() ;
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
                
    	}
    	
    	public static void GetFile() throws Exception{
    		 File file = new File("c:\test.java");
             FileInputStream fis = new FileInputStream(file);
             BufferedReader br = new BufferedReader(new InputStreamReader(fis));
             //Unhandled exception type FileNotFoundException
             //2 quick fixed available: add Throwable ; surrownd try/catch
             String line = br.readLine();
             System.out.println(line);
             //输出结果:heheheheh
             
    	}
    
    }
    

      

    2. 在当前要出现异常的代码块周围,try --catch

    package com.throwable;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class ExcetionDemo2 {
    
    	/**
    	 * @param args
    	 * @throws Exception 
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    			GetFile() ;
    	}
    	
    	public static void GetFile(){
    		 File file = new File("c:\test.java");
             FileInputStream fis;
    		try {
    			fis = new FileInputStream(file); 
    			BufferedReader br = new BufferedReader(new InputStreamReader(fis)); 
    			 //Unhandled exception type FileNotFoundException
    			//2 quick fixed available: add Throwable ; surrownd try/catch
                String line;
    			line = br.readLine();
                System.out.println(line);
             //输出结果:heheheheh
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        
    	}
    
    }
    

      

  • 相关阅读:
    Pandas 合并,连接,连接和比较
    根据条件在Pandas DataFrame中选择行
    pandas DataFrame.where() 检查一个或多个条件的数据帧,并相应地返回结果
    获取包含给定子字符串的Pandas DataFrame中的所有行
    Pandas Series.str.contains
    Python | 查找给定字符串中字符的位置
    Python中的Enumerate()
    Python –遍历NumPy中的列
    Boost 编译
    opencv 提取RGB并用cocos2d-x 纹理方式显示
  • 原文地址:https://www.cnblogs.com/childhooding/p/4639587.html
Copyright © 2011-2022 走看看