- 使用throws关键字抛出异常
Throws 关键字通常被用来声明方法时,用来指定方法可能抛出的异常。多个异常可以使用逗号分隔。
创建类ThrowsDemo类,在该类中创建方法pop(),该方法中抛出NegativeArraySizeException异常,在主方法中调用该方法,并实现异常处理。
package com.gx.vo;
public class ThrowsDemo{
static void pop() throws NegativeArraySizeException{
//定义方法并抛出NegativeArraySizeException异常
int[]arr=new int[-3];
}
public static void main(String[] args) {//主方法
try {//try处理异常信息
pop();
} catch (NegativeArraySizeException e) {
System.out.println(“pop()方法抛出的异常”);
}
}
}
运行结果如下图:
使用throws关键字将异常抛出给上一级后,如果不想处理该异常,可以继续向上一级抛出异常,但最终能够有处理该异常代码。
2.使用throw关键字抛出异常
Throw关键字通常用于方法体中,并且抛出一个异常对象。程序在执行到throw语句立即终止,它后面的语句都不执行。通常throw抛出异常后,如果想在上一级代码中捕获并处理异常,则需要在抛出异常的方法中使用throws关键字在方法的声明中指明要抛出的异常;如果要捕获throw抛出异常,则必须使用try-catch语句块。
2.1.下面通过实例实例介绍throw的用法,创建自定义异常类MyException,继承Exception:
public class MyExceptionextends Exception{//创建自定义异常类
String message;//定义string类型变量
public FinalDate(String Error){//父类方法
message=Error;
}
public String getMessage(){//覆盖getMessage()方法
return message;
}
}
2.2使用throw关键字捕获异常。创建OutException类,该类中的quotient()方法传递两个int型参数,如果其中的一个参数为负数,则会抛出MyException异常,最后在main方法中捕获异常
public class Demo {
static int quotien(int x,int y)throws MyExecption{//定义方法抛出异常
if (y<0) {//判断参数是否小于0
throw new MyExecption(“除数不能是负数”);//异常信息
}
return x/y;//返回值
}
public static void main(String[] args) {//主方法
try {//try语句包含可能发生异常的语句
int result=quotien(3, -1);//调用方法quotien
}catch (MyExecption e) {//处理自定义异常
System.out.println(e.getMessage());//输出异常信息
}catch (ArithmeticException e) {//处理ArithmeticException异常
System.out.println(“除数不能为0”);
}
catch (Exception e) {//处理其他异常
System.out.println(“程序出现其他异常”);
}
}
}
运行结果如下:
本实例使用多个catch语句来捕获异常,如果调用quotien(3,-1)方法,将发生MyException异常,程序调转catch(MyException e)代码块中执行;如果调用quotien(5,0)方法将发生ArithmeticException异常,程序调转catch(ArithmeticException e)代码块中执行;如果还有其他异常发生,将使用catch(Exception e)捕获异常。由于Exception是所有异常类父类,如果将catch(Exception e)代码块放在其他两个异常代码块的前面,后面代码块将没有意义,所有catch语句的顺序不能调换
throws和throw关键字抛出异常描述
最新推荐文章于 2023-03-20 16:30:00 发布