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 异常。如果捕获到异常,我们就打印出异常的堆栈跟踪。

相关推荐
清水白石0082 小时前
Python 编程实战全景:从基础语法到插件架构、异步性能与工程最佳实践
开发语言·python·架构
yaoxin5211233 小时前
390. Java IO API - WatchDir 示例
java·前端·python
Halo_tjn4 小时前
Java 基于字符串相关知识点
java·开发语言·算法
梦想的颜色4 小时前
java 利用redis来限制用户频繁点击
java·开发语言
报错小能手4 小时前
Swift 并发 Combine响应式框架
开发语言·ios·swift
万法若空5 小时前
C++ <memory> 库全方位详解
开发语言·c++
代码中介商5 小时前
C++ 类型转换深度解析:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
青小莫5 小时前
C++之string(OJ练习)
开发语言·c++·stl
freshman_y5 小时前
一篇介绍C语言中二级指针和二维数组的文章
c语言·开发语言
-Marks-5 小时前
【C++编程】STL简介 --- (是什么 | 版本发展历程 | 六大组件 | 重要性缺陷以及如何学习)
开发语言·c++·学习·stl·stl版本