アットウィキロゴ

例外処理

try-catch-finally

例外チェックを設定
  1. import java.io.*;
  2.  
  3. class sample04{
  4. public static void main(String[] args){
  5.  
  6. try{
  7.  
  8. InputStreamReader isr = new InputStreamReader(System.in);
  9. BufferedReader br = new BufferedReader(isr);
  10.  
  11. System.out.print("入力=");
  12. String a = br.readLine();
  13. int b = Integer.parseInt(a);
  14. System.out.println("出力=" + b);
  15.  
  16. }catch(Exception ex){
  17. System.out.println(ex.toString());
  18.  
  19. }finally{
  20. System.out.println("終了");
  21.  
  22. }
  23.  
  24. }
  25. }
  26.  
try~catch~finally
try  :チェックする処理を記述
catch :例外時の処理を記述
finally:完了時の処理を記述

throws

例外が発生した場合、呼び出し元のメソッドでチェック
  1. import java.io.*;
  2.  
  3. class sample05{
  4. public static void main(String[] args){
  5.  
  6. try{
  7. int a = input();
  8. System.out.println("出力=" + a);
  9.  
  10. }catch(Exception ex){
  11. System.out.println(ex.toString());
  12.  
  13. }finally{
  14. System.out.println("終了");
  15.  
  16. }
  17.  
  18. }
  19.  
  20. public static int input() throws Exception{
  21.  
  22. InputStreamReader isr = new InputStreamReader(System.in);
  23. BufferedReader br = new BufferedReader(isr);
  24.  
  25. System.out.print("入力=");
  26. String a = br.readLine();
  27.  
  28. int b = Integer.parseInt(a);
  29.  
  30. return b;
  31.  
  32. }
  33. }
  34.  
メソッド名に
throws 例外処理名:で上位のメソッドへ例外ハンドラを渡す

throw

例外処理を作成
  1. import java.io.*;
  2.  
  3. class sample06{
  4. public static void main(String[] args){
  5.  
  6. try{
  7. check();
  8.  
  9. }catch(sampleException ex1){
  10. System.out.println(ex1.toString());
  11.  
  12. }catch(Exception ex99){
  13. System.out.println(ex99.toString());
  14.  
  15. }finally{
  16. System.out.println("終了");
  17.  
  18. }
  19.  
  20. }
  21.  
  22. public static void check() throws sampleException{
  23.  
  24. int a = 10;
  25. if(a == 10){
  26. throw new sampleException("例外発生");
  27. }
  28.  
  29. }
  30. }
  31.  
  32. // 追加例外処理
  33. class sampleException extends Exception{
  34. sampleException(String str){
  35. super(str);
  36. }
  37. }
  38.  
Exceptionを継承することで独自の例外処理を作成出来る
throw new 例外処理名で任意に例外処理を起こすことが出来る





最終更新:2012年09月02日 10:21