编写一个方法,比较两个字符串。假如其中一个字符串为空,会产生nullpointerexception异常,在方法声明中通告该异常,并在适当时候触发异常,然后编写一个程序捕获该异常。
时间: 2023-04-29 12:02:17 浏览: 98
以下是一个比较两个字符串的方法,如果其中一个字符串为空,会抛出NullPointerException异常:
```
public static boolean compareStrings(String str1, String str2) throws NullPointerException {
if (str1 == null || str2 == null) {
throw new NullPointerException("字符串不能为空");
}
return str1.equals(str2);
}
```
在方法声明中使用了throws关键字通告了该异常。在方法中,如果有一个字符串为空,就会抛出NullPointerException异常,并且异常信息为"字符串不能为空"。
以下是一个捕获该异常的程序:
```
public static void main(String[] args) {
try {
String str1 = "hello";
String str2 = null;
boolean result = compareStrings(str1, str2);
System.out.println(result);
} catch (NullPointerException e) {
System.out.println("捕获到异常:" + e.getMessage());
}
}
```
在程序中,我们调用了compareStrings方法,并传入了一个非空字符串和一个空字符串。由于空字符串会抛出NullPointerException异常,所以我们使用try-catch语句捕获了该异常,并输出了异常信息。输出结果为:
```
捕获到异常:字符串不能为空
```