非常全面的Java异常处理(全文干货,值得收藏)

 更新时间:2020年11月23日 07:51  点击:1379

一.初始Java异常

1、对异常的理解:异常:在Java语言中,将程序执行中发生的不正常情况称为“异常”。(开发过程中的语法错误和逻辑错误不是异常)

2、Java程序在执行过程中所发生对异常事件可分为两类:

  •  Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError和OOM。一般不编写针对性 的代码进行处理。
  • Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。例如:
  • 空指针访问
  • 试图读取不存在的文件
  • 网络连接中断
  • 数组角标越界

3、运行时异常和编译时异常

运行时异常

  • 是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常。java.lang.RuntimeException类及它的子类都是运行时异常。
  • 对于这类异常,可以不作处理,因为这类异常很普遍,若全处理可能会对程序的可读性和运行效率产生影响。

编译时异常

  • 是指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一 般性异常。编译器要求Java程序必须捕获或声明所有编译时异常。
  • 对于这类异常,如果程序不处理,可能会带来意想不到的结果。

在这里插入图片描述

二.Error和Exception

1.Error

代码示例一:java.lang.OutOfMemoryError(堆溢出)

public class ErrorTest {
 public static void main(String[] args) {
 //堆溢出:java.lang.OutOfMemoryError
 Long[] arr = new Long[1024*1024*1024];
 }
}

运行结果:

在这里插入图片描述

代码示例二:java.lang.StackOverflowError(栈溢出)

public class ErrorTest {
 public static void main(String[] args) {

 //栈溢出:java.lang.StackOverflowError
 main(args);
 }
}

运行结果:

在这里插入图片描述

2.Exception(运行时异常和编译时异常)

运行时异常

 /* ******************以下是运行时异常****************** */
 //ArithmeticException
 @Test
 public void test1(){
 int num1 = 3;
 int num2 = 0;
 int num3 = 3 / 0;
 }

 //InputMismatchException
 @Test
 public void test2(){
 Scanner scanner = new Scanner(System.in);
 int i = scanner.nextInt();
 System.out.println(i);
 scanner.close();
 }

 //NumberFormatException
 @Test
 public void test3(){
 String str = "abcd";
 int num = Integer.parseInt(str);
 }

 //ClassCastException
 @Test
 public void test4(){
 Object obj = new Boolean(true);
 String str = (String)obj;
 }

 //IndexOutOfBoundsException
 @Test
 public void test5(){
 ArrayIndexOutOfBoundsException
 Byte[] bytes = new Byte[3];
 System.out.println(bytes[4]);
 }

 //NullPointerException
 @Test
 public void test6(){
 int[] arr = null;
 System.out.println(arr[1]);
 }

编译时异常

/* ******************以下是编译时异常****************** */
 @Test
 public void test7(){
 File file = new File("a.txt");
 //java.io.FileNotFoundException
 FileInputStream fis = new FileInputStream(file);
 //java.io.IOException
 int date = fis.read();
 while (date != -1){
  System.out.println((char)date);
  date = fis.read();
 }

 fis.close();
 }

ps:对于编译时异常,我们需要异常处理

三.异常处理:抓抛模型

 1.抓抛解释

过程一:“抛”:程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象, 并将此对象抛出;一旦抛出对象以后,其后的代码就不再执行。

关于异常对象的产生:

① 系统自动生成的异常对象

② 手动的生成一个异常对象,并抛出(throw)

过程二:“抓”:可以理解为异常的处理方式:① try-catch-finally ② throws

2.try-catch-finally的使用

try{
//可能出现异常的代码

}catch(异常类型1 变量名1){
//处理异常的方式1
}catch(异常类型2 变量名2){
//处理异常的方式2
}catch(异常类型3 变量名3){
//处理异常的方式3
}
…
finally{
//一定会执行的代码
}

说明:

  1. finally是可选的。
  2. 使用try将可能会出现异常的代码段包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,去catch中进行匹配
  3. 一旦try中的异常对象匹配到某一个catch时,就进入catch中进行异常的处理。一旦处理完成,就跳出当前的
    try-catch结构(在没有写finally的情况)。继续执行其后的代码
  4. catch中的异常类型如果没有子父类关系,则谁声明在上,谁声明在下无所谓。
    catch中的异常类型如果满足子父类关系,则要求子类一定声明在父类的上面。否则,报错
  5. 常用的异常对象处理的方式: ① String getMessage() ② printStackTrace()
  6. 在try结构中声明的变量,再出了try结构以后,就不能再被调用
  7. try-catch-finally结构可以嵌套
  8. finally中声明的是一定会被执行的代码。即使catch中又出现异常了,try中有return语句,catch中有return语句等情况。
  9. 像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动的回收的,我们需要自己手动的进行资源的释放。此时的资源释放,就需要声明在finally中。

示例一:

@Test
public void test1(){
 String str = "abcd";
 int num = 1314;
 try {
 num = Integer.parseInt(str);

 System.out.println("进入try代码块!");
 }catch (NumberFormatException e){
 System.out.println("出现数值转换异常了!");
 System.out.println(e.getMessage());
 e.printStackTrace();
 System.out.println("该catch语句块将要执行完了!");
 } catch (NullPointerException e){
 System.out.println("出现空指针异常!");
 } catch (Exception e){
 System.out.println("出现异常了");
 }finally {
 System.out.println("执行finally语句了!");
 }
 System.out.println(num);
}

输出结果:

在这里插入图片描述

示例二:

 @Test
 public void test2(){
  File file = new File("a.txt");
  FileInputStream fis = null;
  try {
   fis = new FileInputStream(file);
   int date = fis.read();
   while(date != -1){
    System.out.println((char)date);
    date = fis.read();
   }


  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }catch (IOException e){
   e.printStackTrace();
  }finally {
   System.out.println("执行finally语句了!");
   try {
    fis.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

输出结果:

在这里插入图片描述

总结:

  • 使用try-catch-finally处理编译时异常,是得程序在编译时就不再报错,但是运行时仍可能报错。相当于我们使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现。
  • 开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-finally了。针对于编译时异常,我们说一定要考虑异常的处理。

3.throws + 异常类型的使用

"throws + 异常类型"写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出。异常代码后续的代码,就不再执行!

try-catch-finally:真正的将异常给处理掉了。
throws的方式只是将异常抛给了方法的调用者。 并没有真正将异常处理掉。

子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型(子类重写的方法也可以不抛出异常)

public class SuperClass {
 public void method() throws IOException {

 }
}

class SubClass extends SuperClass{
 //报错,子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型
// public void method() throws Exception{
//
// }

 public void method() throws FileNotFoundException{

 }
}

开发中如何选择使用try-catch-finally 还是使用throws? 如果父类中被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throws,意味着如果

子类重写的方法中有异常,必须使用try-catch-finally方式处理。执行的方法a中,先后又调用了另外的几个方法,这几个方法是递进关系执行的。我们建议这几个方法使用throws

的方式进行处理。而执行的方法a可以考虑使用try-catch-finally方式进行处理。

代码示例:

public class ErrorThrows {
 public static void method1() throws IOException {
  File file = new File("a.txt");
  FileInputStream fileInputStream = new FileInputStream(file);
  
  int data = fileInputStream.read();
  while(data != -1){
   System.out.println((char)data);
   data = fileInputStream.read();
  }
  fileInputStream.close();
 }
 
 public static void method2() throws IOException {
  method1();
 }
 
 public static void method3() throws IOException {
  method1();
 }

 public static void main(String[] args) {
  try {
   method3();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

4.手动抛出一个异常类对象(throw关键字使用)

代码示例:

public class ReturnException {
 static void method1(){
  try{
   System.out.println("进入方法1");
   throw new RuntimeException("手动抛出异常");
  }catch (Exception e){
   e.printStackTrace();
   System.out.println(e.getMessage());
  } finally {
   System.out.println("执行finally语句了!");
  }
 }

 public static void main(String[] args) {
  method1();
 }
}

输出结果:

在这里插入图片描述

四.自定义异常类

自定义异常类,有如下三步骤:

  • 继承于现有的异常结构:RuntimeException 、Exception
  • 提供全局常量:serialVersionUID
  • 提供重载的构造器

自定义异常类:

public class MyExceptionClass extends Exception{

 static final long serialVersionUID = -5641210210148784L;

 public MyExceptionClass() {
 }

 public MyExceptionClass(String message) {
  super(message);
 }
}

手动抛出上述自定义的异常类对象:

public class MyExceptionTest {

 static void method1() throws MyExceptionClass {
  Scanner scanner = new Scanner(System.in);

  System.out.println("请输入大于0的数据:");
  double next = scanner.nextDouble();
  if(next >0){
   System.out.println("您输入的数据为:"+next);
  }else {
   throw new MyExceptionClass("您输入的数据不满足要求!");
  }
 }

 public static void main(String[] args) {
  try {
   method1();
  } catch (MyExceptionClass myExceptionClass) {
   myExceptionClass.printStackTrace();
  }
 }
}

运行结果:

在这里插入图片描述

到此这篇关于非常全面的Java异常处理的文章就介绍到这了,更多相关Java异常处理干货内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

[!--infotagslink--]

相关文章