java的异常处理try, catch,throw,throws和finally

来源:互联网 发布:js name属性选择器 编辑:程序博客网 时间:2024/05/21 15:40

Java异常处理主要通过5个关键字控制:try、catch、throw、throws和finally。try的意思是试试它所包含的代码段中是否会发生异常;而catch当有异常时抓住它,并进行相应的处理,使程序不受异常的影响而继续执行下去;throw是在程序中明确引发异常;throws的作用是如果一个方法可以引发异常,而它本身并不对该异常处理,那么它必须将这个异常抛给调用它的方法;finally是无论发不发生异常都要被执行的代码

关键字:try, catch,throw,throws和finally
用法如下:
1、try出现在方法体中,它自身是一个代码块,表示尝试执行代码块的语句。如果在执行过程中有某条语句抛出异常,那么代码块后面的语句将不被执行。
2、throw出现在方法体中,用于抛出异常。当方法在执行过程中遇到异常情况时,将异常信息封装为异常对象,然后throw。
3、throws出现在方法的声明中,表示该方法可能会抛出的异常,允许throws后面跟着多个异常类型
4、catch出现在try代码块的后面,自身也是一个代码块,用于捕获异常try代码块中可能抛出的异常。catch关键字后面紧接着它能捕获的异常类型,所有异常类型的子类异常也能被捕获。
5、finally 一定被执行,任何执行try 或者catch中的return语句之前,都会先执行finally语句,如果finally存在的话。如果finally中有return语句,那么程序就return了,所以finally中的return是一定会被return的,
编译器把finally中的return实现为一个warning。

异常类型

  • Exception 异常层次结构的根类

    ArithmeticException 算数错误情形

    ArrayIndexOutOfBoundsException 数组下标越界

    NullPointerException 尝试访问null对象成员

    ClassNotFoundException 不能加载所需的类

    InputMismatchException 欲得到的数据类型与实际输入的类型不匹配

    IllegalArgumentException 方法接受到非法参数

    ClassCastException 对象强制类型转换出错

    NumberFormatException 数字格式转换异常
    例子 try and catch

package Test;import java.util.Scanner;public class Test_Test {    public static void main(String[] args) {        Scanner input =new Scanner(System.in);        System.out.println("请输入被除数:");        try {            int num1=input.nextInt();            System.out.println("请输入除数:");            int num2=input.nextInt();            System.out.println(String.format("%d / %d = %d",                    num1, num2, num1 / num2));        }catch (Exception e) {            System.err.println("出现错误:被除数和除数必须是整数,"+        "除数不能为零。");            System.out.println(e.getMessage());    }}

try-catch-finally

package Test;import java.util.Scanner;public class Test_Test {    public static void main(String[] args) {        Scanner input =new Scanner(System.in);        System.out.println("请输入被除数:");        try {            int num1=input.nextInt();            System.out.println("请输入除数:");            int num2=input.nextInt();            System.out.println(String.format("%d / %d = %d",                    num1, num2, num1 / num2));        }catch (Exception e) {            System.err.println("出现错误:被除数和除数必须是整数,"+        "除数不能为零。");            System.out.println(e.getMessage());        }            finally{            System.out.println("Thanks");        }    }}

try-catch-finally 程序块的流程大致分为两种情况:

  1. 如果try块中所有语句正常执行完毕,那么finally块就会被执行。
  2. 如果try语句在执行过程中碰到异常,无论这种异常能否被catch块捕获到,都将执行finally块中的代码。

try—catch-catch-finally(多重catch块)

package Test;import java.util.InputMismatchException;import java.util.Scanner;public class Test_Test {    public static void main(String[] args) {        Scanner input =new Scanner(System.in);        System.out.println("请输入被除数:");        try {            int num1=input.nextInt();            System.out.println("请输入除数:");            int num2=input.nextInt();            System.out.println(String.format("%d / %d = %d",                    num1, num2, num1 / num2));        }catch (InputMismatchException e) {            System.err.println("被除数和除数必须是整数。");        }         catch (ArithmeticException e) {                System.err.println("除数不能为零。");         }        catch (Exception e) {            System.err.println("其他未知异常。");            System.out.println(e.getMessage());        }            finally{            System.out.println("Thanks");        }    }}

例题
除数为零异常处理
本题目要求读入2个整数A和B,然后输出它们的商。要求使用try-catch-finally进行异常处理。当除数为0时,输出 “Not divided by 0

must process

END”等信息。其中catch子句输出“Not divided by 0”,finally子句输出”must process”,main方法最后一句输出”END”。

输入格式:

输入在一行中给出2个整数A和B。

输出格式:

对每一组输入,在一行中输出A/B的值。

输入样例:

在这里给出一组输入。例如:

10 5
输出样例:

在这里给出相应的输出。例如:

10/5=2
must process
END

throw——抛出异常
抛出异常有三种形式,一是throw,一个throws,还有一种

系统自动抛异常。

public class Test2 {    public static void main(String[] args) {        int a = 5, b =0;          System.out.println(5/b);     }}

throw抛出异常:

throw是语句抛出一个异常。
语法:throw (异常对象);

package Test;public class Test2 {    public static void main(String[] args) {        String s = "abc";          if(s.equals("abc")) {              throw new NumberFormatException();        } else {              System.out.println(s);          }      }}

throws——声明异常
throws是方法可能抛出异常的声明。(用在声明方法时,表示该方法可能要抛出异常)
语法:(修饰符)(方法名)([参数列表])[throws(异常类)]{……}

package Test;public class Test2 {    public static void main(String[] args) {        try {            Test3();        } catch (NumberFormatException e) {            System.err.println("非数据类型不能转换。");        }    }    public static void Test3() throws NumberFormatException{          String s = "abc";          System.out.println(Double.parseDouble(s));      }  }

如果在一个方法体中抛出了异常,那么我们就可以通过throws——声明异常来通知调用者,非常方便。

throws表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某种异常对象。

最后说一句,try-catch-finally虽好用,但是如果是滥用,这样只是会让程序的可读性变的很糟糕,当程序报错,就无法快速准确的定位了,物尽其用 人尽其才嘛!

import java.util.Scanner;public class Main {static int avg(int number1,int number2) throws Exception{    if(number2==0){        throw new Exception("");    }    return (number1/number2);}public static void main(String[] args){    Scanner in = new Scanner(System.in);    int num1,num2;    try{        num1 =in.nextInt();        num2 =in.nextInt();        int result = avg(num1,num2);        System.out.println(num1+"/"+num2+"="+result);    }catch(Exception e){        System.out.println("Not divided by 0");    }    finally    {        System.out.println("must process");    }    System.out.println("END");}}

FROM https://www.cnblogs.com/wcf6676/p/4905909.html

阅读全文
0 0
原创粉丝点击