Java编程中使用throw关键字抛出异常的用法简介
作者:小和尚敲代码 时间:2023-08-27 17:04:19
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()方法抛出的异常");//输出异常信息
}
}
}
标签:Java,throw,异常
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C++选择排序算法实例
2021-10-27 21:43:33
springboot-mybatis/JPA流式查询的多种实现方式
2021-07-07 17:25:51
![](https://img.aspxhome.com/file/2023/2/76292_0s.jpg)
java中JVM中如何存取数据和相关信息详解
2023-08-10 03:49:46
![](https://img.aspxhome.com/file/2023/8/58048_0s.jpg)
详解C#中的依赖注入和IoC容器
2023-03-11 09:05:19
![](https://img.aspxhome.com/file/2023/2/82232_0s.png)
图解JVM垃圾内存回收算法
2023-10-13 17:24:35
![](https://img.aspxhome.com/file/2023/4/64804_0s.jpg)
详解SpringBoot中Session超时原理说明
2022-01-24 06:40:49
C#泛型集合类System.Collections.Generic
2023-02-24 19:21:18
快速排序算法在Java中的实现
2022-05-25 01:06:15
![](https://img.aspxhome.com/file/2023/7/69317_0s.png)
Android调试出现The selected device is incompatible问题解决
2023-08-11 12:58:34
![](https://img.aspxhome.com/file/2023/5/137935_0s.jpg)
Java文件读写IO/NIO及性能比较详细代码及总结
2021-11-28 12:56:30
java8从list集合中取出某一属性的值的集合案例
2023-04-30 01:51:49
![](https://img.aspxhome.com/file/2023/9/92659_0s.jpg)
Spring MVC处理方法返回值过程解析
2022-11-05 23:47:14
java中方法递归的简单示例
2022-11-25 11:45:12
![](https://img.aspxhome.com/file/2023/1/66041_0s.png)
详解Spring Boot Profiles 配置和使用
2021-10-05 22:54:57
c# 实现语音聊天的实战示例
2021-11-18 06:29:20
![](https://img.aspxhome.com/file/2023/2/91312_0s.png)
详解如何为SpringBoot项目中的自定义配置添加IDE支持
2021-10-07 05:51:01
![](https://img.aspxhome.com/file/2023/5/104205_0s.png)
基于java math API 的详细解释说明
2021-10-04 06:51:44
SpringBoot如何实现定时任务示例详解
2023-10-11 23:24:42
![](https://img.aspxhome.com/file/2023/3/84613_0s.png)
java统计文件中每个字符出现的个数
2021-12-22 06:43:42
springboot Interceptor拦截器excludePathPatterns忽略失效
2023-08-11 19:44:46
![](https://img.aspxhome.com/file/2023/9/74879_0s.jpg)