欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JAVA--异常基础介绍 try-catch-finally和throws基础讲解

程序员文章站 2022-06-17 19:08:52
异常定义:是指程序在运行中的出现的错误,例如:在进行除法运算时,若除数为0,则运行JAVA是会自动抛出算数异常。JAVA 异常 :也是古通过一个对象来表示的,程序运行时抛出的异常,实际上就是一个异常对象,该对象中不仅封装了错误的信息,还提供了一些处理方法。......

异常

定义:是指程序在运行中的出现的错误,例如:在进行除法运算时,若除数为0,则运行JAVA是会自动抛出算数异常。

JAVA 异常 :也是通过一个对象来表示的,程序运行时抛出的异常,实际上就是一个异常对象,该对象中不仅封装了错误的信息,还提供了一些处理方法。

异常的分类(Throwable)

                   1: 异常(Exception) :合理的应用程序可能需要捕获的问题     举例:NullPointerException  (空指针异常类)    是可预料的

                   2:错误(Error) :合理的应用程序不应该试图捕获的问题     举例:*Error  ( 栈内存溢出)   是不可预料的

               分类解析:  我们作为程序员只需要认识关于我们程序上的东西,也就是可预料的,也就是异常 ,是在我们解决范围之内的问题。

                                  错误是不可期的是具有不确定性发生的 ,也是在代码程序范围之外的,只需了解即可。

常见的异常类列表:

异常类名称

异常类含义

ArithmeticException 算术异常类
ArraylndexOutOfBoundsException 数组下标越界异常类

ArrayStoreException

将与数组类型不兼容的值赋值给数组元素时抛出的异常
ClassCastException 类型强制转换异常
IndexOutOfBounchsException 当某对象的索引超出范围时抛出异常
NegativeArraySizeException 建立元素个数为负的数组异常类
NullPointException 空指针异常
NumberFormatException 字符串转换为数字异常类
SecurityException Applet试图执行浏览器的安全设置不允许的动作
StringIndexOutBounchsException 程序试图访问字符串中字符不存在的字符位置
OutOfMemoryException 分配给新对象的内存太小
SockedException 不能正常完成Socked操作
ProtocolException 网络协议有错误
ClassNotFoundException 未找到相应的异常类
EOFException 文件结束异常
FileNotFoundException 文件未找到异常
illegalAccessException 访问某类被拒绝时抛出的异常
InstantiationException

试图通过new Instance()方法创建一个抽象

类或抽象接口的实例时出现的异常

IOException 输入、输出异常
NoSuchFileException 字段未找到异常
NoSuchMethodException 方法未找到异常
SQLException 操作数据库异常
ClassNotFoundException 文件未找到异常类

注意:若不知道代码抛出是那种异常,可以指定它们的父类 Throwable 和 Exception。

异常的处理方式:

JVM默认的异常处理方式:在控制台打印错误信息,并终止程序

开发中异常的处理方式:

           1:try....catch(finally):捕获,自己处理

           2:throws:抛出,交给调用者处理   

     1:try....catch(finally):捕获,自己处理

finlly子句:与try catch语句连用,不管try catch 语句是否执行顺利,finlly语句都会被执行。

代码格式: 

try {
     //尝试执行的代码
} catch (Exception e) {
    //出现可能的异常之后的处理代码
} finally{
    //一定会执行的代码,如关闭资源
}
-------------
//try catch 可以同时存在多个catch 语句
try{
}
catch{
}
catch{
}
catch{
}

对于处理方式进行例题讲解

题:当定义一个数,让这个数除以0出现的代码问题如何解决。

public class trycatch {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a =10 / 0;
		System.out.println("a:"+a);
	}

}
------------------------------------
结果在控制台出现异常代码:
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at 异常.trycatch.main(trycatch.java:9)

通过解决异常处理方式一 try....catch 进行解决

public class trycatch {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {  //写尝试要执行的代码
		int a =10 / 0;
		System.out.println("a:"+a);
		}catch (Exception e) { //写出现问题后的解决方案
			System.out.println("出现异常错误");
	}finally {
		System.out.println("这yi行出现吗?");
	}
		System.out.println("这二行出现吗?");
}
}
--------------------------------------
输出结果:
出现异常错误
这yi行出现吗?
这er行出现吗?

方式一的特点:

1:“这二行出现吗?” 这一行的输出 说明:当异常问题被解决后 会继续执行下面代码

2:finally {} 代码可以有,同样也可以没有区别在于:即使  try  catch 中有没有 return  finally中的语句依然被执行通过代码进行解释:

代码一:
public class trycatch {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {  //写尝试要执行的代码
		int a =10 / 0;
		System.out.println("a:"+a);
		}catch (Exception e) { //写出现问题后的解决方案
			System.out.println("出现异常错误");
                return;
	}finally {
		System.out.println("这yi行出现吗?");
	}
		System.out.println("这二行出现吗?");
}
}
-------------------------------------------------
输出结果:
出现异常错误
这yi行出现吗?
代码二:

public class trycatch {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {  //写尝试要执行的代码
		int a =10 /10;
		System.out.println("a:"+a);
		return;
		}catch (Exception e) { //写出现问题后的解决方案
			System.out.println("出现异常错误");
			
	}finally {
		System.out.println("这yi行出现吗?");
	}
		System.out.println("这er行出现吗?");
}
}
--------------------------
输出结果:
a:1
这yi行出现吗?

以上代码说明return 可以决定着语句结束后是否向下执行,当有finally语句后会执行finally语句内容但不会执行方式一语句之外的代码。

解释:return 是结束语句的用语,当出现异常时会执行异常语句,如果判定没有异常就是执行try中的输出语句后,之后return ,说明代码结束,之后再执行finally语句内容。

方法一执行流程:

先执行try{}语句的内容,看是否会出现问题(异常)

         没有:直接执行finally语句的内容

         有:直接跳转到catch{}语句中开始执行,完成之后再执行finally{}语句中的内容。

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

方法二:throws:抛出,交给调用者处理。

               public  void 方法名() throws Exception{  }

拓展延伸:使用throw也可以抛出异常,与throws不同的是throw在方法体内,throws在方法体外。

 

错误例题代码:

public class throws1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		show();

	}
	public static void show() {
		int n= 10/0;
		System.out.println("n"+n);
	}

}
错误示例:两处错误
1:int n =10 /0
2:show():main函数错误

让方法抛出异常,只需修改public static void show()

改为:

public static void show () throws Exception{}
public class throws1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//需求:通过main 函数调用show()方法
		show();  //这样出现时会显示错误:Unhandled exception type Exception
				//因为show()已经抛出异常,作为调用者(main函数)必须处理这个异常
				//这就是说抛出异常交给调用者处理。

	}
	public static void show () throws 	Exception {
		int n= 10/0;
		System.out.println("n"+n);
	}

}
----------------------
//解决方案一:
//你把异常抛给我,我也抛,给别人。 有main函数抛给JVM
//代码:

public class throws1 {

	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		//需求:再main 函数调用show()方法
		show();  
		System.out.println("看看我执行了吗");

	}
	public static void show () throws 	Exception {
		int n= 10/0;
		System.out.println("n"+n);
	}

}
运行结果:
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at 异常.throws1.show(throws1.java:15)
	at 异常.throws1.main(throws1.java:8)
代码只显示异常的问题,并没有输出打印“看看我执行了吗”这行
-----------------------
方案二:
public class throws1 {

	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		//需求:再main 函数调用show()方法
        try{
		show(); 
         }
        catch { 
            system.out.println("代码出问题了吗");
          }
		System.out.println("看看我执行了吗");

	}
	public static void show () throws 	Exception {
		int n= 10/0;
		System.out.println("n"+n);
	}

}
----------------------
执行结果:
代码出问题了吗
看看我执行了吗

方法二特点总结:

通过throws 解决时,执行结束后代码不会再继续执行

通过try.....catch 解决时,执行结束后代码会再继续执行。

使用异常代码(try catch finally 和 throws 和 throw)的注意事项:

1:

不能单独使用try catch 或 finally 语句块,否则编译出错。

File file = new File("d:\cat.txt");
try{
FileOutputStream out = new FileOutputStream(file);
out.write("start".getBytes);
}
打出这样的代码就会报错
Syntax error, insert "Finally" to complete TryStatement

2:

Try语句块既可以只使用catch语句,也可以只使用finally语句。当与catch语句块一起时,可以存在多个catch语句,而只能存在一个finally语句,当catch和finally语句一起使用时,finally语句必须放在catch语句后面。

3:

try至于catch语句使用时,可以使程序在发生异常时抛出异常,并继续执行方法中的其他代码。

package 异常;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class zhuyi {

	public static void main(String[] args) throws IOException{
		// TODO Auto-generated method stub
		File file = new File("D:\\cat.txt");
		try{
		FileOutputStream out = new FileOutputStream(file);
		out.write("start".getBytes());
		out.close();
		out.write("end".getBytes());
		}
		finally {
			System.out.println("看看这行执行了吗");
		}
	}

}
-------------------------
看看这行执行了吗
Exception in thread "main" java.io.IOException: Stream Closed
	at java.base/java.io.FileOutputStream.writeBytes(Native Method)
	at java.base/java.io.FileOutputStream.write(FileOutputStream.java:334)
	at 异常.zhuyi.main(zhuyi.java:16)
//通过结果得知抛出异常后继续执行其他代码
//而且还抛出异常

4:

try只与catch语句块使用时,可以使用多个eatch语句块来捕获try语句块中可能发生的多种异常。异常发生后,Java虚拟机会由上而下来检测当前catch语句块所捕获的异常是否与try语向块中发生的异常匹配,若匹配,则不再执行其他的catch语句块。如果多个catch语句块捕获的是同种类型的异常,则捕获子类异常的catch语句块要放在捕获父类异常的catch语句块前面。

File file = new File("D:\\cat.txt");
		try{
		FileOutputStream out = new FileOutputStream(file);
		out.write("start".getBytes());
		out.close();
		out.write("end".getBytes());
		}
		catch (Exception e) {
			System.out.print("父类异常");
		}
		catch (IOException e) {
			System.out.print("子类异常");
		}
	}
代码报错:Unreachable catch block for IOException. It is already handled by the catch block for Exception

5:

在try 语句块中声明的是局部变量,只在当前try语句块中有效,在其后的catch finally语句块或其他位置都不能访问变量。但在try catch和finally语句块之外的声明的变量,可在try catch 和finally语句块中使用。

6:

在使用throw语句抛出一个异常对象,该语句后面的代码将不会被执行。

try {
}
catch (){
throw e;
system.out.println("会不会被执行"); //这行代码将不会被执行
}

 

 

 

本文地址:https://blog.csdn.net/m0_52479012/article/details/109841752