当前位置: 移动技术网 > IT编程>开发语言>Java > java--异常处理

java--异常处理

2019年06月23日  | 移动技术网IT编程  | 我要评论

异常处理

我们在写代码时,经常出现的一些小问题,为了方便我们处理,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);
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网