JAVA 100道题(17)

17.创建一个方法,接受一个整数作为参数,并检查它是否为正数。如果不是,则抛出自定义异常。

首先,你需要定义一个自定义的异常类。在Java中,你可以通过继承 Exception 类来创建自定义异常。然后,你可以创建一个方法,该方法接受一个整数作为参数,并检查它是否为正数。如果不是,则抛出你的自定义异常。

以下是一个示例:

复制代码

java复制代码

|---|-------------------------------------------------------------------------------------|
| | // 定义自定义异常类 |
| | class NotPositiveException extends Exception { |
| | public NotPositiveException(String message) { |
| | super(message); |
| | } |
| | } |
| | |
| | // 定义方法 |
| | public class Main { |
| | public static void main(String[] args) { |
| | try { |
| | checkPositiveNumber(0); |
| | } catch (NotPositiveException e) { |
| | e.printStackTrace(); |
| | } |
| | } |
| | |
| | public static void checkPositiveNumber(int number) throws NotPositiveException { |
| | if (number <= 0) { |
| | throw new NotPositiveException("The number is not positive."); |
| | } else { |
| | System.out.println("The number is positive."); |
| | } |
| | } |
| | } |

在这个例子中,NotPositiveException 是一个自定义的异常类,它继承了Java的 Exception 类。checkPositiveNumber 方法接受一个整数作为参数,并检查它是否为正数。如果 number 小于或等于0,那么它将抛出一个 NotPositiveException 异常。在 main 方法中,我们尝试调用 checkPositiveNumber 方法,并使用 try-catch 语句捕获并处理可能抛出的 NotPositiveException 异常。如果捕获到异常,我们就打印出异常的堆栈跟踪。

相关推荐
想回家的一天3 小时前
ECONNREFUSED ::1:8000 前端代理问题
开发语言
cike_y3 小时前
Mybatis之解析配置优化
java·开发语言·tomcat·mybatis·安全开发
Jay_Franklin5 小时前
SRIM通过python计算dap
开发语言·python
是一个Bug5 小时前
Java基础50道经典面试题(四)
java·windows·python
Slow菜鸟5 小时前
Java基础架构设计(三)| 通用响应与异常处理(分布式应用通用方案)
java·开发语言
消失的旧时光-19435 小时前
401 自动刷新 Token 的完整架构设计(Dio 实战版)
开发语言·前端·javascript
wadesir5 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
我是Superman丶5 小时前
《Spring WebFlux 实战:基于 SSE 实现多类型事件流(支持聊天消息、元数据与控制指令混合传输)》
java
tap.AI5 小时前
RAG系列(二)数据准备与向量索引
开发语言·人工智能
廋到被风吹走5 小时前
【Spring】常用注解分类整理
java·后端·spring