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