java 异常抛出_Java 异常抛出

Java面向对象设计 - Java异常抛出

如果一段代码可能抛出一个已检查的异常,我们有两个选择:使用try-catch块处理已检查的异常。

在方法/构造函数声明中用throws子句指定。

语法

throws子句的一般语法是() throws{

}

关键字throws用于指定throws子句。

throws子句放在方法参数列表的右括号之后。

throws关键字后面是以逗号分隔的异常类型列表。

例子

下面的代码展示了如何在方法的声明中使用throws子句。import java.io.IOException;

public class Main {

public static void readChar() throws IOException {

int input = System.in.read();

}

}

这里是显示如何使用它的代码。

例2import java.io.IOException;

public class Main {

public static void readChar() throws IOException {

int input = System.in.read();

System.out.println(input);

}

public static void main(String[] args) {

try {

readChar();

} catch (IOException e) {

System.out.println("Error occurred.");

}

}

}

上面的代码生成以下结果。

36f89a002732c740bf1a5a4e73c86d26.png

例3

我们可以继续抛出异常。import java.io.IOException;

public class Main {

public static void readChar() throws IOException {

int input = System.in.read();

System.out.println(input);

}

public static void main(String[] args) throws IOException {

readChar();

}

}

上面的代码生成以下结果。

7c94ecc894d72abf2b0fcb7bf4ae151e.png

抛出异常

我们可以使用throw语句在我们的代码中抛出异常。

throw语法的语法是throw ;

throw是一个关键字,后面是一个对可抛出对象的引用。

throwable对象是一个类的实例,它是Throwable类的子类,或Throwable类本身。

以下是throw语句的示例,它抛出一个IOException:// Create an object of IOException

IOException e1 = new IOException("File not found");

// Throw the IOException

throw e1;

以下是throw语句的示例,它抛出一个IOException:// Throw an IOException

throw new IOException("File not found");

如果我们抛出一个被检查的异常,我们必须使用try-catch块来处理它,或者在方法或构造函数声明中使用throws子句。

如果您抛出未经检查的异常,这些规则不适用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值