import java.util.Scanner;
public class Demo {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Please input positive number:");
int input = scanner.nextInt();
if (input > 0){
System.out.println("Number: " + input);
} else {
assert (input > 0): "執行有誤....";
System.out.println("Error : " + input);
}
}
}
2015年10月7日 星期三
Assertion 用法
Java 例外處理--AutoCloseable
有 catch 敘述:
沒有 catch 敘述(利用 throws,丟給上頭去傷腦筋...)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class OpenFileDemo{
public static void main(String[] args){
System.out.println("About to open a file...");
try (InputStream in = new FileInputStream("hello.txt")){
System.out.println("File is opened..");
int data = in.read();
} catch (FileNotFoundException e){
System.out.println(e.getMessage());
} catch (IOException e){
System.out.println(e.getMessage());
}
}
}
沒有 catch 敘述(利用 throws,丟給上頭去傷腦筋...)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class ThrowDemo {
public static void main(String[] args){
try {
int data = readByteFromFile();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
private static int readByteFromFile() throws FileNotFoundException, IOException {
try(InputStream in = new FileInputStream("a.txt")){
System.out.println("File is opening...");
return in.read();
}
}
}
2015年9月9日 星期三
Java 例外處理
Java 例外處理(基本處理方式):
使用 throws & throw :
Multi-Exception 的用法:
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;
}
}
訂閱:
文章 (Atom)