題目要求:
編寫一個方法,比較兩個字符串。假如其中一個字符串爲空, 會產生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) ;
}
}