Exception mechanism (abnormal classification, and treatment, getMessage, printStackTrace)

(All figures screenshots, as well as information notes, comes from the power node, to learn for their own use)
1. What anomaly?
The first exception is the simulation of the real world "abnormal" event
second, java through the 'class' way to simulate an exception
in the java.lang package has a description of the exception
third category is to create objects
NullPointerException e = 0x1234; // instantiate here equivalent to the class of the exception class is instantiated, it becomes a real presence of abnormal events
this object must be NullPointerException type
this object is indicating the presence of abnormal events real
NullPointerExceptions is a kind of anomaly

	“抢劫”就是一类异常
	张三被抢劫就是一个异常时间。

2. The exception mechanism was the role?
java language provides us with a complete exception handling mechanism,
the role is: after the occurrence of an abnormal event program, detailed information for our output,
programmers can program through some processing this information, making the program more robust

public class Test{

public static void main(String[] args){
	int a = 5;
	int b = 0;
	int c = a/b;  //程序语法没问题,编译能通过,但是不符合数学规则,无法运行

	System.out.println("hello");  //	如果上面的异常没有处理,不会接着执行下面的语句,JVM会做主自动								退出该语句
	/*Exception in thread "main" java.lang.ArithmeticException: / by zero
 at 异常机制/test.Test01.main(Test01.java:8)*/	系统报的异常反馈
 	本质:程序执行过程中发生了算数异常这个事件,JVM为我们创建了一个ArithmeticException类型的对象。并且这个对象中包含了详细的异常信息,并且JVM将这个对象中的信息输出到控制台。


}

}

//一下是我们在知道异常后,对异常进行处理,通过改变代码对这些异常处理
public static void main(String[] args){
	int a = 11;
	int b = 0;
	if(b!=0){
		System.out.println(a+"/"+b+"="+a/b);
	}else
	{
		System.out.println("b不能为0");			//这就是异常处理,这样就规避了异常的出现
	}
}

Abnormal inheritance structure diagram
Throwable () all exceptions and errors superclass are inherited with him
Here Insert Picture Description

Here Insert Picture Description
Exception is divided into lower (abnormal) abnormal abnormal compilation and runtime
exception (there are many) to compile and run exception (RuntimeException) E is
the difference between compile-time and run-time anomaly abnormal
abnormal, requiring programmers to write all of the compiler program stage, he must be treated, if not addressed, the compiler can not pass. There are two ways to handle exceptions: catch and throw statements. Capture: try ... catch ..., is to use the throw statement throws keyword thrown in the position statement on the method,
an exception occurs when compiling a higher probability

Abnormal, runtime exceptions programmers write stage does not need to process it all subclasses of RuntimeException are running
the chance of occurrence is relatively low run

处理异常有两种方式:
	1.声明抛出:throws
	2.捕捉:	try...catch..
	
	以下程序演示第一种方式:声明抛出,在方法声明的位置上使用throws关键字向上抛出异常。
public class Test{
	public static void  main(String[] args)
	{
		//思考:java编译器是如何知道一下的代码执行过程中可能出现异常
		//java编译器是如何知道这个异常发生的几率比较高呢?
		
		FileInputstream fis = new FileInputstream("c:/ab.txt")

		//其实当我查API文档对于FileInputStreamd类的定义时候,有如下代码
		public FileInputStream​(String name) throws FileNotFoundException 该类在定义的时候后面就		跟了throws,并且throws后面跟的是一个 FileNotFoundException异常,该异常继承于编译异常。
		所以调用该类,就必须要有对于的异常处理机制,
	}
}
//以上程序编译不通过
/*
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type FileNotFoundException at 异常机制/运行异常.Tets.main(Tets.java:6)
*/

The first program demonstrates what an exception handling: throw statement, using the throws keyword position on the method declaration thrown up

If there are no throws, that is no exception handling mechanism, the compiler will not pass, but then with the exception handling mechanism, compiled by the statement before the exception occurs is normal operation, but after the statement in question can not pass

public class Test{
	//public static void main(String[] args) throws IOException
	//public static void main(String[] args) throws Exception
	public static void main(String[] args) throws FileNoFoundException{ 
	FileInputStream fis = new FileInputStream("c:/ab.txt");
	}

}

Deep throws
throws throw up on behalf of representatives call its methods, need throwsn followed Exception class
after when an exception occurs, throws will be consistent throwing up, but will not be resolved if the Internet has been cast, if not resolved, will eventually JVM and the program ends
abnormalities by try ... catch ... to solve

public class Test{
	public static void main(String[] args)	 throws FileNotFoundException{
		m1();
		//使用throws处理异常不是真正处理异常而是推卸责任。
		//谁调用的就会抛给谁。
		//上面的m1方法如果出现了异常,因为采用的是上抛,给了JVM,JVM遇到这个异常就会退出JVM,下面的代码不会执行
		System.out.println();
	}
	public static void m1() throws FileNotFoundException{
		m2();
	}
	public static void m2() throws FileNotFoundException{   // 由于m3方法上有throws所以上抛,`调用它的m2()也需要用throws后面跟上异常处理机制
		m3();
	}
	public static void m3() throws FileNotFoundException{  //由于FileInputStream有throws,所以													要在m3方法后用throws处理
		new FileInputStream("c:/ab.txt");  //有FileInputStream 但是没有处理机制,所以直接这样写										会报错
	}

}

这是程序后的报错信息
在程序运行过程中发生了FileNotFoundException类型的异常
JVM为我们创建了一个FileNotFoundException类型的对象。
该对象中携带以下的信息:
//JVM负责将该对象的信息打印到控制台
//并且JVM停掉了程序的运行

Exception in thread "main" java.io.FileNotFoundException: c:\ab.txt (系统找不到指定的文件。) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:213) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:110) at 异常机制/运行异常.Test.m3(Test.java:21) at 异常机制/运行异常.Test.m2(Test.java:18) at 异常机制/运行异常.Test.m1(Test.java:15) at 异常机制/运行异常.Test.main(Test.java:8)

The second way to handle exceptions: the try ... the catch ... catch ...
1.catch statement can be written more quickly
2. But from top to bottom catch, the type of exception must from small to large types of abnormal capture.
3.try ... catch ... to perform up to a catch block. After the execution try ... catch ... is over

Speaking in front, there is an exception would create an object, catch inside the exception object is created to capture assigned to the inside of the variable

语法:
	try{
		可能出现异常的代码;
		
	}catch(异常类型 变量){  //该变量内存地址指向堆中的那个对象是“异常类型”的实例化
		
		处理异常的代码;
	
	}
	catch(异常类型 变量){
	
	处理异常代码;
	
	}
	1.catch语句块可以写多个
public class ExceptionTest{

try{
	FileInputStream fis = new FileInputStream("c:/ab.txt");
}catch(ArithmeticException e ) {//这样写是不行的,因为这样捕获是错误的,因为我们希望捕捉的是FileNotFoundException异常,但是这里却捕获的是数学异常,所以我们在选择要捕获的异常的时候,一定要先看try里面可能出现异常的代码会出现哪种异常,再决定捕获哪种异常
}


//以下程序可以通过,捕获的异常和可能出现的异常相同
try{
	FileInputStream fis = new FileInputStream("c:/ab.txt");
}catch(FileNotFoundException e ){
}



try{ 
	FileInputStream fis = new FileInputStream("c:/ab.txt");
	fis.read();   //read()这个方法是FileInputStream继承与他的父类InputStream,然而InputStream 					throws的方法为IOException
}catch(FileNotFoundException e )
{
}catch(IOException e){
}


//以下方法编译也可通过,但是可能处理起来不具体比较模糊

try{

	 FileInputStream fis = new FileInputStream("c:/ab.txt");
	 fis.read();
 } catch(IOException e){
 }




//编译无法通过,
//catch可以写多个,但是必须从上到下,从小到大捕捉
try{

 FileInputStream fis = new FileInputStream("c:/ab.txt");
 fis.read();
 }catch( IOException e){
 
 }catch(FileNotFoundException e){

}

}



//这里要注意的是,当try内部有语句异常,捕捉处理后,try后面的语句将不会再执行,所以这里响应了前面的多个catch语句只执行一个的条件

try{ 
 FileInputStream fis = new FileInputStream("c:/ab.txt"); 
  fis.read(); 
   }catch( IOException e){ 
     System.out.println("读取路径有错误");
    }catch(FileNotFoundException e){
    System.out.println("err!")} 

About printStackTrace application methods and getMessage

public class ExceptionTest{
	public static void main(String[] args)
	{
		try{
			FileInputStream fis = new FilesInputStream("c:/ab.txt");
		
			//JVM为我们执行了以下代码
		//	FileNotFoundException e = new FileNotFoundException("c:/ab.txt 找不到指定文件")
		//这个会继承关系,构造方法不断的往上传,传到Throwable里的getMessage方法里面
		//是由JVM帮我们赋值再不断网上传
		}
		catch(FileNotFoundException e){
			//打印异常堆栈信息
			//一般情况下都会使用该方式去调试程序
			e.printStackTrace();  //如果不加这个方法,不会打印下面的错误信息,系统会直接向下运行,不会给报错信息
		/*
		 * java.io.FileNotFoundException: sd (系统找不到指定的文件。) at
		 * java.base/java.io.FileInputStream.open0(Native Method) at
		 * java.base/java.io.FileInputStream.open(FileInputStream.java:213) at
		 * java.base/java.io.FileInputStream.<init>(FileInputStream.java:155) at
		 * java.base/java.io.FileInputStream.<init>(FileInputStream.java:110) at
		 * 异常机制/运行异常.Test01.main(Test01.java:9)
		 */
			//另外一种方法
			String ms = e.getMessage();  //getMessage这个方法是从throwable那里一路继承过来的
			System.out.println(msg);
			//会有如下的报错信息
			//sd (系统找不到指定的文件。)
		}
		//在catch里面有了具体的处理方式后,后面的代码会继续执行
		System.out.println("ABC");
	}

}


Published 28 original articles · won praise 0 · Views 424

Guess you like

Origin blog.csdn.net/wenshao007/article/details/104407435