异常类精练——编写一个方法,比较两个字符串。假如其中一个字符串为空, 会产生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) ;				
		}
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45696288/article/details/106994058#comments_22498720