zoukankan      html  css  js  c++  java
  • java--异常处理

    异常处理

    我们在写代码时,经常出现的一些小问题,为了方便我们处理,java为我们提供了异常机制
    捕获异常与抛出异常

    //捕获异常格式:
    	 try {
             //可能出错的语句
         } catch (出错的类型 出错的对象) {
             //出错后的处理
         }
    
    //eg:
    	try{
    		System.out.println(1);
    		System.out.println(2/0);
    		System.out.println(3);
    	} catch(ArithmeticException ae){
    		System.out.println(4);
    	}
    	System.out.println(5);
    	// 1  4  5
    
    //eg2:
    	try{
    		//String s=null;
    		//s.length();
    		char[] chs = new char[5];
    		System.out.println(chs[5]);
    	}catch(NullPointerException ne){
    		System.out.println("空指针异常");
    	}catch(Exception e){					//当有其他未知异常时,实例化异常的父类对象,捕获未知异常
    		System.out.println("其他异常");
    	}
    
    
    
    //void printStackTrace(java.io.PrintWriter s) 
    //通用方式,打印异常类型,位置,与java虚拟机自己捕获异常类型不同的是,这个异常打印后,还会继续执行下面的语句
    	try{
    		char[] chs = new char[5];
    		System.out.println(chs[5]);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	System.out.println("----");
     
    
    //finally: 不论是否捕获到异常都会执行的部分,常用于释放资源,清理垃圾
    	try(){
    		//有可能出现问题的代码;
    	} catch(异常对象){
    		//处理异常
    	} finally{
    		//释放资源;
    		//清理垃圾
    	}
    
    
    

    finallyDemo

    //鲁棒版文件写入
    	public static void main(String[] args) {
    		function("a.txt");
    	}
    	
    	public static void function(String filename){
    		FileWriter fw = null;
    		try {
    			//System.out.println(1/0);;
    			fw = new FileWriter(filename);
    			fw.write("hello world");
    			fw.write("hello world");
    			//fw.write(2/0);
    			fw.write("hello world");
    			fw.write("hello world");
    		} catch (IOException e) {
    			e.printStackTrace();
    		}finally{
    			try {
    				if(fw!=null)
    					fw.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    			
    		}
    		
    	}
    

    抛出异常(throw)

    throw new RuntimeException("抛出运行时异常");  //抛出运行时异常
    throw new Excepption("抛出编译时异常");
    
    //自定义异常类  继承RuntimeException 或者是 Exception
    public class MyException extends RuntimeException{
    	
    	public MyException()
    	{
    		super();
    	}
    	
    	public MyException(String s)
    	{
    		super(s);
    	}
    }
    
    
  • 相关阅读:
    PAT甲级1091Acute Stroke
    PAT甲级1076Forwards on Weibo
    PAT甲级1131Subway Map
    PAT甲级1130Infix Expression
    PAT甲级1103Integer Factorization
    PAT甲级1034Head of a Gang
    Blender删除历史材质球未用材质球
    王者荣耀 花木兰 水晶猎龙者 同人3D壁纸 木兰小哥哥也有拧不开瓶盖的时候,嘿嘿嘿 家居服 减布料
    王者荣耀 嫦娥 同人 3D渲染 壁纸 家居服 减布料
    联考6
  • 原文地址:https://www.cnblogs.com/selfdef/p/11072238.html
Copyright © 2011-2022 走看看