这篇文章主要介绍了简单了解Java关键字throw和throws的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
抛出异常有三种形式
一、系统自动抛异常
当程序语句出现一些逻辑错误、主义错误或类型转换错误时,系统会自动抛出异常:(举个栗子)
public static void main(String[] args) {
int a = 5, b =0;
System.out.println(5/b); // 此处系统会自动抛出ArithmeticException异常
//function();
}
二、throw
throw是语句抛出一个异常,一般是在代码块的内部,当程序出现某种逻辑错误时由程序员主动抛出某种特定类型的异常
public static void main(String[] args) {
String s = "abc";
if(s.equals("abc")) {
throw new NumberFormatException();
} else {
System.out.println(s);
}
//function();
}
运行时,系统会抛出如下异常:
Exception in thread "main" java.lang.NumberFormatException at......
三、throws
当某个方法可能会抛出某种异常时用于throws 声明可能抛出的异常,然后交给上层调用它的方法程序处理
public class testThrows(){
public static void function() throws NumberFormatException {
String s = "abc";
System.out.println(Double.parseDouble(s));
}
public static void main(String[] args) {
try {
function();
} catch (NumberFormatException e) {
System.err.println("非数据类型不能强制类型转换。");
//e.printStackTrace();
}
}
运行结果如下:
非数据类型不能强制类型转换
四、throw与throws的比较
五、编程习惯:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。