/*1、編寫應(yīng)用程序,從命令行傳入兩個整型數(shù)作為除數(shù)和被除數(shù)卓研。要求程序中捕獲NumberFormatException 異常和ArithmeticException 異常秧骑,而且無論在哪種情況下动壤,“總是被執(zhí)行”這句話都會在控制臺輸出机打。 */
import java.util.Scanner;
public class NumberExeption {
//正則表達式數(shù)字驗證
public static boolean isNumber(String str)
? ? {
? ? ? ? java.util.regex.Pattern pattern=java.util.regex.Pattern.compile("[0-9]*");
? ? ? ? java.util.regex.Matcher match=pattern.matcher(str);
? ? ? ? return match.matches();
? ? }
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("請輸入第一個數(shù)字:");
String s1=scan.next();
System.out.println("請輸入第二個數(shù)字");
String s2=scan.next();
int n1,n2;
try {
n1=Integer.parseInt(s1);
n2=Integer.parseInt(s2);
System.out.println(n1/n2);
} catch (NumberFormatException|ArithmeticException e) {
e.printStackTrace();
}
finally {
System.out.println("It is always running!");
}
}
}
運行圖:
/*2辙售、編寫一個檢查給定的數(shù)字的數(shù)據(jù)類型是否為byte的程序肛鹏,
* 如果此數(shù)字超出byte數(shù)據(jù)類型表示的數(shù)的范圍聋迎,則引發(fā)用戶自定義的異常ByteSizeException,
* 并顯示相應(yīng)的錯誤信息(知識點:自定義異常)
* 步驟1:創(chuàng)建用戶自定義異常類ByteSizeException
* 步驟2:在main方法中編寫邏輯代碼
* 步驟3:運行并測試
*/
public class ByteSizeException extends Exception {
public ByteSizeException() {
super("此數(shù)字超出了byte數(shù)據(jù)類型表示的數(shù)的范圍");
}
}
測試程序:
public class ByteTest {
public static void ByteEcep(int number) throws ByteSizeException {
if (number > 127 || number <= -128) {
throw new ByteSizeException();
}
}
public static void main(String[] args) {
try {
ByteEcep(565);
} catch (ByteSizeException e) {
e.printStackTrace();
}
}
}
運行圖:
/*
* 3脂矫、編寫一個方法,比較兩個字符串霉晕。假如其中一個字符串為空庭再,
* 會產(chǎn)生NullPointerException異常,在方法聲明中通告該異常牺堰,
* 并在適當時候觸發(fā)異常拄轻,然后編寫一個程序捕獲該異常。
*/
public class NullPoint {
public static void NullPointed(String s1, String s2) throws NullPointerException {
if (s1 == null || s2 == null) {
throw new NullPointerException();
} else {
}
}
public static void main(String[] args) {
try {
String a = null;
String b = "bdn";
NullPointed(a, b);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
運行圖: