2015年9月9日 星期三

Java 例外處理

Java 例外處理(基本處理方式):
import java.util.Scanner;

public class ErrorDemo{

 public static void main(String[] args){
 
  int input = 0;
  Scanner scanner = new Scanner(System.in);
  System.out.print("請輸入一個整數:");
  try{
   input = scanner.nextInt();
  } catch (Exception e){
   System.out.println("請輸入整數!");
  }
 }
}

使用 throws & throw :
public class TestArray{

 int [] intArray;
    public TestArray(int size){
  intArray = new int[size];
 }
 
 public void addElement(int index, int value) throws RuntimeException{
  intArray[index] = value;
  throw new ArrayIndexOutOfBoundsException();
 }
}

public class ExceptionDemo{

 public static void main(String[] args){
 
  TestArray myTestArray = new TestArray(5);
  try {
   myTestArray.addElement(5, 23);
  } catch (RuntimeException e){
   System.out.println("超出陣列大小!");
  }
 }
}

Multi-Exception 的用法:
import java.io.*;

public class MultiExceptionDemo{

 public static void main(String[] args){
 
  try{
   createFile();
  } catch (IOException ex1){
   System.out.println(ex1);
  } catch (IllegalArgumentException ex2){
   System.out.println(ex2);
  } catch (Exception ex3){
   System.out.println(ex3);
  }
 }
 
 public static void createFile() throws IOException{
  File test = new File("C://workspace//test.txt");
  File temp1 = test.createTempFile("te123",null,test);
  System.out.println("Temp filename is " + temp1.getPath());
  int[] myInt = new int[5];
  myInt[5] = 25;
 }
}