try-catch异常处理

一.概述

我们在编程时,往往会出现各种错误与异常,在java中,当某一方法出现错误时,编译器会创建一个异常对象,并把它传递给正在运行的系统。例如,我们在如下的例子中有一处错误。

public class Dem
{
   public static void main(String[] args){
      
      int s1=Integer.parseInt("20L");
      System.out.println(s1);
}
}      

                                                                                                  示例一

在本例中我们将字符串转化为整型数,由于"20L"中含有字母,所以无法转换为整型,因此系统会提示如下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "20L"
	at java.base/java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.base/java.lang.Integer.parseInt(Unknown Source)
	at java.base/java.lang.Integer.parseInt(Unknown Source)
	at tast.java.Dem.main(Dem.java:99)

NumberFormatException: For input string表示字符串转换为数字抛出的异常
 

二.捕捉异常

因而我们在实际操作中可以使用try-catch语句来捕捉异常。try语句块中存放的是可能会发生异常的java语句,而catch语句则用来激发被捕获的异常,在该结构中最后还有一个finally语句块,无论try语句块是否退出,都会执行finally语句

在此我们对示例一的代码进行改进,如下:

public class Dem
{
   public static void main(String[] args){
      try{
      int s1=Integer.parseInt("20L");
      System.out.println(s1);}
      catch(Exception e){
    	  e.printStackTrace();
      }
      finally {
    	  System.out.println("无论try是否异常,对我没有影响");
    	  
      }
}
}

                                                                                                   示例2

java.lang.NumberFormatException: For input string: "20L"
	at java.base/java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.base/java.lang.Integer.parseInt(Unknown Source)
	at java.base/java.lang.Integer.parseInt(Unknown Source)
	at tast.java.Dem.main(Dem.java:99)
无论try是否异常,对我没有影响

Exception是try代码块传递给catch代码块的变量类型,e是变量名

getMessage():输出错误性质

toString():给出异常的类型与性质

printStackTrace():指出异常的性质、类型、栈层次及出现在程序中的位置

三.throws/throw抛出异常

由于Exception类是所有异常类的父类,因此我们可以通过继承Exception类来自定义异常类

class MyException extends Exception
{
	public MyException(String ErrorMessage)
	{
		super(ErrorMessage);
	}
}
class Student
{
	public int speak(int m,int n)throws MyException
	{
		if(m>1000)
		{	
		  throw new MyException("抛出了自定义异常类对象");
		}
		return m/n;
			
	}
}
public class Dem
{
	public static void main(String[] args)
	{
		int m=1001;
		int n=1;
		Student stu=new Student();
		for(int i=0;i<2;i++)
		{
		try {
				stu.speak(m--,n--);
			} catch (MyException e) {
				System.out.println("成功捕捉到自定义异常类的错误");
			}catch(Exception e) {
				//捕捉到自定义异常类之外的错误
				System.out.println("程序发生了其他异常");
			}finally {
				System.out.println("运行完毕\n");
			}
		}
		
	}
}

                                                                                             示例三

运行结果:

成功捕捉到自定义异常类的错误
运行完毕

程序发生了其他异常
运行完毕

在本例中当m=1001,n=1时,满足m>1000条件,因此直接将MyException异常类对象抛给speak方法调用者,而第二次m=1000,n=0时程序直接返回m/n,此时0为被除数,显而是算数错误,因而此时生成ArithmeticException算数异常类对象,所以第一个catch语句并未捕捉到,而第二个catch语句中的Exception异常类便可以捕捉到。如果将Exception放在第一个catch语句中,则MyException类将永远得不到执行,因为Exception是所有异常类的父类。

注:本文中知识点难免会有遗漏,还请多多指教^.^

猜你喜欢

转载自blog.csdn.net/f_IT_boy/article/details/81744264