例外処理メカニズム
1.例外をスローします
2.例外をキャッチします
5つのキーワードを処理する例外
try、catch、finally、throw、throws
コード例:
package com.exception;
public class Test {
public static void main(String[] args) {
int a=10;
int b=0;
try{//监控区域
System.out.println(a/b);
}catch(ArithmeticException e){//捕获异常 catch(想要捕获的异常类型)
System.out.println("程序出现异常,变量b不能为0");
}finally{//善后处理工作
System.out.println("finally");
}
}
}
出力サンプル
コード例
package com.exception;
public class Test {
public static void main(String[] args) {
try{//监控区域
new Test().a();
}catch(Error e){//捕获异常 catch(想要捕获的异常类型)
System.out.println("程序出现异常,栈溢出");
}finally{//善后处理工作
System.out.println("finally");
}
}
public void a(){
b();
}
public void b(){
a();
}
}
出力例
複数の例外をキャッチしたい場合、例外は小さいものから大きいものまであります
ショートカットキー:control + alt + T
積極的にスローする例外は、通常、メソッドで使用されます
コード例:
package com.exception;
public class Test {
public static void main(String[] args) {
new Test().test(1,0);
}
public void test(int a,int b){
if(b==0){
throw new ArithmeticException();
}
}
}
出力例
このメソッドが例外を処理できないと仮定すると、のコード例は上向きにスローします。
package com.exception;
public class Test {
public static void main(String[] args) {
try {
new Test().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test(int a,int b)throws ArithmeticException{
if(b==0){
throw new ArithmeticException();
}
}
}
サンプル出力: