Java编程中使用throw关键字抛出异常的用法简介
更新时间:2015年11月12日 17:45:07 作者:小和尚敲代码
这篇文章主要介绍了Java编程中使用throw关键字抛出异常的用法,是Java入门学习中的基础知识,需要的朋友可以参考下
throw抛出异常的方式比较直接:
if(age < 0){
throw new MyException("年龄不能为负数!");
}
来看一个例子:
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);
}
}
}
运行结果如下:

java中可以对一个方法在定义时就进行异常的声明,而后在实现时可以利用throw具体的抛出异常。
ppublic class Shoot { 创建类
static void pop() throws NegativeArraySizeException {
//定义方法并抛出NegativeArraySizeException异常
int [] arr = new int[-3];//创建数组
}
public static void main(String[] args) {//主方法
try {
pop(); //调用pop()方法
} catch (NegativeArraySizeException e) {
System.out.println("pop()方法抛出的异常");//输出异常信息
}
}
}
相关文章
SpringBoot+MybatisPlus+Mysql+JSP实战
这篇文章主要介绍了SpringBoot+MybatisPlus+Mysql+JSP实战,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-12-12
spring cloud升级到spring boot 2.x/Finchley.RELEASE遇到的坑
这篇文章主要介绍了spring cloud升级到spring boot 2.x/Finchley.RELEASE遇到的坑,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-08-08
SpringBoot使用Spring Cache高效处理缓存数据
Spring Cache是一个框架,只要简单加一个注解,就能实现缓存功能,本文主要介绍了SpringBoot使用Spring Cache高效处理缓存数据,感兴趣的可以了解一下2023-11-11


最新评论