異常的處理方式
對于編譯期異常處理有兩種不同的處理方式
1 使用 try { } catch { } finally 語句塊處理它
2 在函數(shù)簽名中使用 throws 聲明 交給函數(shù)調(diào)用者去處理
try catch finally 塊
try catch finally 塊 是異常的捕捉,其本質(zhì)是判斷
基本語言如下:
try{
可能出現(xiàn)異常的代碼(包括不會出現(xiàn)異常的代碼)
} catch (Exception e){
//括號里面接收try代碼塊中出現(xiàn)的異常類型
如果出現(xiàn)異常時的處理代碼
}finally{
不管代碼是正常執(zhí)行還是出現(xiàn)異常需要處理,finally 代碼塊中的代碼最終都會執(zhí)行
}
Main
// try...cath...finally 演示
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("請輸入被除數(shù):\n");
try {
int num1 = in.nextInt();
System.out.println("請輸入除數(shù):\n");
int num2 = in.nextInt();
System.out.println(num1 + "/" + num2 + "=" + num1/ num2);
}catch (Exception e){
System.out.println("出現(xiàn)錯誤嫡霞,被除數(shù)與除數(shù)必須是整數(shù),除數(shù)不能為零");
e.printStackTrace();
}finally {
in.close();
System.out.println("感謝使用本程序");
}
}
}
運行結(jié)果一.png
TryDemo
public class TryDemo {
Scanner in = new Scanner(System.in);
public static void main(String[] args) {
//使用 throw 和 throws 進行演示
TryDemo demo = new TryDemo();
try {
demo.divide();
} catch (Exception e){
System.out.println("出現(xiàn)錯誤,被除數(shù)與除數(shù)必須是整數(shù)答渔,且除數(shù)不能為零");
e.printStackTrace();
} finally {
demo.in.close();
System.out.println("感謝使用本程序");
}
}
/**
*
* 輸入被除數(shù)與除數(shù)蚯涮,計算結(jié)果并輸入
*
* @ throws Exception
*/
public void divide() throws Exception{
System.out.println("請輸入被除數(shù)");
int num1 = in.nextInt();
System.out.println("請輸入除數(shù)");
int num2 = in.nextInt();
System.out.println(num1+"/"+num2 +"=" + num1/num2);
}
}
運行結(jié)果二.png
Student
public class Student {
private String name = "";
private String sex = "name";
private int age;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getSex(){
return sex;
}
public void setSex(String sex) throws Exception{
if ("name".equals(sex) || "woman".equals(sex)){
this.sex = sex;
}else {
throw new Exception("sex is \"man\"or \"woman\"!");
}
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age ;
}
public void print(){
System.out.println("我是" + getName() +",性別" + getSex() +"推捐,今年" + getAge() + "歲");
}
public void getName(String 張三) {
}
public void getAge(int i) {
}
}
/**
* 捕獲throws 拋出的異常
*/
class Test{
public static void main(String[] args) {
Student zhangsan = new Student();
zhangsan.getName("張三");
zhangsan.getAge(22);
try {
zhangsan.setSex("男性");
} catch (Exception e){
e.printStackTrace();
}
}
}
運行結(jié)果三.png