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

相关推荐
dgvri4 分钟前
比较Spring AOP和AspectJ
java
eggwyw7 分钟前
springboot和springframework版本依赖关系
java·spring boot·后端
流水迢迢lst1 小时前
靶场练习day15--php反序列化
开发语言·php
于先生吖2 小时前
国际版JAVA婚恋交友系统源码:多语言适配,可商用的跨境婚恋解决方案
java·大数据·交友
fengci.2 小时前
ctfshow(web入门)279-286
java·开发语言·学习
fy121632 小时前
navicat15安装破解
java
TON_G-T2 小时前
javascript中 Iframe 处理多端通信、鉴权
开发语言·前端·javascript
周淳APP2 小时前
【JS之闭包防抖节流,this指向,原型&原型链,数据类型,深浅拷贝】简单梳理啦!
开发语言·前端·javascript·ecmascript
ok_hahaha2 小时前
java从头开始-苍穹外卖day05-Redis及店铺营业状态设置
java·开发语言·redis