0
点赞
收藏
分享

微信扫一扫

Java-异常处理(一篇讲透)

异常处理



前言

本博主将用CSDN记录软件开发求学之路上亲身所得与所学的心得与知识,有兴趣的小伙伴可以关注博主!
也许一个人独行,可以走的很快,但是一群人结伴而行,才能走的更远!让我们在成长的道路上互相学习,欢迎关注!

一、异常概述与异常体系结构

1. 异常概述

  • 引入
  • 概念

2. 分类

2.1 Error vs Exception

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

(1) Error

(2)Exception

常见Exception
空指针访问
试图读取不存在的文件
网络连接中断
数组角标越界

注意:程序员通常只能处理Exception,而对Error无能为力。

2.2 编译时异常 vs 运行时异常

(1)编译时异常

(2)运行时异常

注意: 捕获错误最理想的是在编译期间,但有的错误只有在运行时才会发生。

3. 常见异常

3.1 分类

(1) java.lang.RuntimeException

(2) java.io.IOExeption

(3) java.lang.ClassNotFoundException
(4) java.lang.InterruptedException
(5) java.io.FileNotFoundException
(6) java.sql.SQLException

3.2 代码演示

public class Order {
    public static void main(String[] args) {
       Object obj = new Date();
       Order order;
       order = (Order) obj;
       System.out.println(order);
     } 
}

在这里插入图片描述

public class IndexOutExp {
   public static void main(String[] args) {
      String friends[] = { "lisa", "bily", "kessy" };
      for (int i = 0; i < 5; i++) {
        System.out.println(friends[i]); // friends[4]?
      }
      System.out.println("\nthis is the end");
   } 
}

在这里插入图片描述

public class NullRef {
   int i = 1;
   public static void main(String[] args) {
     NullRef t = new NullRef();
     t = null;
     System.out.println(t.i);
   } 
}
public class DivideZero {
   int x;
   public static void main(String[] args) {
      int y;
      DivideZero c=new DivideZero();
      y=3/c.x; 
      System.out.println("program ends ok!");
   } 
}

在这里插入图片描述

  public void test1(){		
		String str = "123";
		str = "abc";
		int num = Integer.parseInt(str);						
  }

在这里插入图片描述

public void test1(){
		Scanner scanner = new Scanner(System.in);
		int score = scanner.nextInt();
		System.out.println(score);		
		scanner.close();
}

二、异常处理机制

1. 概述

2. 异常处理机制一:try-catch-finally

2.1 语法格式

 try{
        ...... //可能产生异常的代码
    }
    catch( ExceptionName1 e ){
        ...... //当产生ExceptionName1型异常时的处置措施
    }
    catch( ExceptionName2 e ){
        ...... //当产生ExceptionName2型异常时的处置措施
    } finally{
    ...... //无论是否发生异常,都无条件执行的语句
    } 

2.2 使用

(1)try

(2)catch (Exceptiontype e)

(3)捕获异常的有关信息(写在catch{ }语句中)

(4)finally

2.3 代码演示

//举例一:
/*
例子一使用的异常都是RuntimeException类或是它的子类,这些类的异常的特点是:
即使没有使用try和catch捕获,Java自己也能捕获,并且编译通过(但运行时会发生异常使得程序运行终止)。
*/
public class IndexOutExp {
    public static void main(String[] args) {
         String friends[] = { "lisa", "bily", "kessy" };
         try {
            for (int i = 0; i < 5; i++) {
                System.out.println(friends[i]);
            }
         } catch (ArrayIndexOutOfBoundsException e) {
             System.out.println("index err");
         }
          System.out.println("\nthis is the end");
    } 
}
/*     output:
             lisa
             bily
             kessy
             index err
             this is the end
*/

//举例二:
/*
如果抛出的异常是IOException等类型的非运行时异常,则必须捕获,否则
编译错误。也就是说,我们必须处理编译时异常,将异常进行捕捉,转化为
运行时异常。
*/
public class IOExp {
    public static void main(String[] args) {
       FileInputStream in = new FileInputStream("atguigushk.txt");
       int b;
       b = in.read();
       while (b != -1) {
          System.out.print((char) b);
          b = in.read();
       }
          in.close();
    } 
}

3. 异常处理机制二:声明抛出异常(throws)

3.1 语法格式

public void readFile(String file) throws FileNotFoundException {
    ……
    // 读文件的操作可能产生FileNotFoundException类型的异常
    FileInputStream fis = new FileInputStream(file);
    ……
}

3.2 使用

public class A {
public void methodA() throws IOException {
……
} }
public class B1 extends A {
public void methodA() throws FileNotFoundException {
……
} }
public class B2 extends A {
public void methodA() throws Exception { //报错
……
} }

4. “ try-catch-finally” 与 “throws” 的区别

5.手动抛出异常(throw)

6. 用户自定义异常类

class MyException extends Exception {
      static final long serialVersionUID = 13465653435L;
      private int idnumber;
      public MyException(String message, int id) {
            super(message);
            this.idnumber = id; }
      public int getId() {
            return idnumber;       
      } 
}

public class MyExpTest {
      public void regist(int num) throws MyException {
            if (num < 0)
            throw new MyException("人数为负值,不合理", 3);
            else
            System.out.println("登记人数" + num);
      }
      public void manager() {
            try {
                  regist(100);
            } catch (MyException e) {
                  System.out.print("登记失败,出错种类" +e.getId());
            }
            System.out.print("本次登记操作结束");
      }
      public static void main(String args[]) {
            MyExpTest t = new MyExpTest();
            t.manager();
      } 
}

在这里插入图片描述

举报

相关推荐

0 条评论