java入门基础学习----异常

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Miracle_Gaaral/article/details/82026280

JAVA是采用面向对象的方式来处理异常的。处理过程:

        1.抛出异常: 在执行一个方法时,如果发生异常,则这个方法生成代表该异常的一个对象,停止当前执行路径,并把异常对象提交给JRE;

        2.捕获异常: JRE得到该异常后,寻找相应的代码来处理该异常。JRE在方法的调用栈中查找,从生成异常的方法开始回溯,直到找到相应的异常处理代码为止。

分类:1.Runtime Exception (unchecked Exception)----------由系统自动检测并交给缺省的异常处理程序(用户可不必对其处理)

                       ArithmeticException,  NullPointerException,  ClassCastException,   

                       IndexOutOfBoundsException,  NumberFormatException

             2.Checked Exception------------用户必须捕获对其进行处理

                 

异常的处理办法之一

        捕获异常(try, catch, finally)

        try{

             语句块;    //一个try语句必须带有至少一个catch语句块或一个finally语句块

                  注意:当异常处理代码执行结束后,是不会回到try语句去执行尚未执行的代码      

         }catch(Exception e){

             语句2;  //e.printStackTrace();               e.toString();                  e.getMessage()              这些方法都继承自Throwable类

         }finally{

             语句3;     //有些语句,不管是否发生了异常,都必须要执行,那么就可以把这样的语句放到finally语句块中

                      通常在finally中关闭程序块已打开的资源,比如:文件流、释放数据库连接等

         }

异常处理办法之二

        声明异常: throws 子句       抛出异常,谁调用谁处理

        当Checked Exception产生时,不一定立刻处理它,可以再把异常throws出去;

        如果一个方法抛出多个已检查异常,就必须在方法的首部列出所有的异常,之间以逗号隔开。

package com.kennosaur.exception;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestThrow {
	public static void main(String[] args) {
		String string =null;
		try {
			string = new TestThrow().openFile();
		} catch (FileNotFoundException e) {			
			e.printStackTrace();
		} catch (IOException e) {			
			e.printStackTrace();
		}
		System.out.println(string);
	}
	
	String openFile() throws IOException, FileNotFoundException {
		FileReader reader = new FileReader("d:/a.txt");
		char c = (char)reader.read();
		System.out.println(c);
		return ""+c;
	}
}

        方法重写中声明异常原则:子类声明的异常范围不能超过父类声明的范围

异常处理办法之三----用的很少

        手动抛出异常,throw子句,自己new一个异常对象。

File file = new File("d:/bb.txt");
if(!file.exists()) {
	try {
		throw new FileNotFoundException("File can't be found!");
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
}

自定义异常

猜你喜欢

转载自blog.csdn.net/Miracle_Gaaral/article/details/82026280