异常类精练——编写一个方法,比较两个字符串。假如其中一个字符串为空, 会产生NullPointerException异常

题目要求:

编写一个方法,比较两个字符串。假如其中一个字符串为空, 会产生NullPointerException异常,在方法声明中通告该异常, 并在适当时候触发异常,然后编写一个程序捕获该异常。

public class Main {
		public static void main(String[] args) {
			try {
				int k = pare("abc","");
				System.out.println(k);
			}catch(NullPointerException e) {
				System.out.println(e.getMessage());
			}
		}
		public static int pare(String s1 , String s2) throws NullPointerException{//通告异常//非检查异常可以不用抛出,但题目要求抛出
			if(s1==null || s2 == null )
				throw new NullPointerException("产生了NullPointerException异常") ;
				return s1.compareTo(s2) ;				
		}
}

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章