java编程基础(五)----异常

异常概述:

  • 异常:程序不正常的行为或者状态
  • 异常处理:程序返回安全状态;允许用户保存结果,并以适当方式关闭程序

异常分类:

Error:系统内部错误或者资源耗尽(不用太管);

Exception:程序有关的异常(重点关注);

  • RuntimeException:程序自身的错误(空指针,数组越界....)
  • IOException:外界相关的错误

java程序相关异常又分为:

  • Unchecked Exception:编译器不会辅助检查,需要程序员自己处理(包括Error子类和RuntimeException子类)
  • Checked Exception:编译器会辅助检查的异常,(非RuntimeException的子类)

异常处理

目的

  • 允许用户及时保存结果
  • 抓住异常,分析异常内容
  • 控制程序返回安全状态

具体方法:

try-catch-finally:一种保护代码正常运行的机制。

结构:

  • try...catch(catch可以有多个,下同)
  • try...catch...finally
  • try...finally
  • try必须有,catch和finally至少要有一个
  1. try:正常业务逻辑代码
  2. catch:当try发生异常,将执行catch代码。若无异常,绕之。
  3. finally:当try或catch执行结束后,必须要执行finally。

代码示例:

public class TryDemo {

    public static void main(String[] args) {
        try
        {
            int a = 5/2; //无异常
            System.out.println("a is " + a);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            System.out.println("Phrase 1 is over");
        }
        
        try
        {
            int a = 5/0; //ArithmeticException
            System.out.println("a is " + a);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            System.out.println("Phrase 2 is over");
        }
        
        try
        {
            int a = 5/0; //ArithmeticException
            System.out.println("a is " + a);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            int a = 5/0; //ArithmeticException
        }
        finally
        {
            System.out.println("Phrase 3 is over");
        }
    }
}

 

多catch块处理:

  • catch块可以有多个,每个有不同的入口参数。当已发生的异常和某一个catch块中的形参类型一致,那么将执行该catch块中的代码。如果没有一个匹配,catch不会被触发。最后都进入finally块。
  • 进入catch块后,并不会返回到try发生异常的位置,也不会执行后续的catch块,一个异常只能进入一个catch块。
  • catch块的异常匹配是从上而下进行匹配的。
  • 一般将小的异常写在前面,而一些大(宽泛)的异常写在末尾。

嵌套结构:

try结构中,如果有finally块,finally肯定会被执行。

try-catch-finally每个模块里面会发生异常,所以也可以在内部继续写一个完整的try结构。

try {

    try-catch-finally

}

catch() {

    try-catch-finally

}

finally {

    try-catch-finally

}

throw声明异常(checked exception)

  • 方法存在可能异常的语句,但是不处理,那么可以使用throws来声明异常。
  • 调用带有throws异常的方法,要么处理这些异常,或者再次向外throws,直到main函数为止。

代码示例:

public class ThrowsDemo
{
    public static void main(String [] args)
    {
        try
        {
            int result = new Test().divide( 3, 1 );
            System.out.println("the 1st result is" + result );
        }
        catch(ArithmeticException ex)
        {
            ex.printStackTrace();
        }
        int result = new Test().divide( 3, 0 );
        System.out.println("the 2nd result is" + result );
    }
}
class Test
{
    //ArithmeticException is a RuntimeException, not checked exception
    public int divide(int x, int y) throws ArithmeticException
    {
        int result = x/y;
        return x/y;
    }
}

原文地址:https://www.cnblogs.com/Yunus-ustb/p/12887718.html