异常的第一种用法是Java比C++增加的一种使用方法,但是其抛出异常的方法一般只有直接抛出到method体之外,不能用try catch(原因不明确,可能是因为try catch l里的variables都只能在curly brakets 里使用);如果要将读入文件单独成为一个method的话,抛出的异常需要两次,先抛出到mathod之外,再抛出到main之外。
package myexception;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) throws FileNotFoundException {
String fileName = new String("hello.txt");
File textFile = new File(fileName);
throwEx(textFile);
}
public static void throwEx(File file) throws FileNotFoundException {
Scanner in = new Scanner(file);
int a = in.nextInt();
System.out.println(a);
while (in.hasNext()) {
System.out.println(in.next());
}
in.close();
}
}
抛出异常的传统作用是继承C++的,是终止进程的方法,在不同的Java文件中的异常最终都要在main里再次抛出
import java.io.IOException;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Test test = new Test();
Scanner in = new Scanner(System.in);
try {
test.run(in.nextBoolean());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/
import java.io.IOException;
public class Test {
public void run(boolean a) throws IOException {
/// a is false means this field is wrong , the method need to be
/// terminated by FIleException
if (a)
throw new FIleException(“a is true”);
/// a is false means this field is wrong , the method need to be
/// terminated by IOException
if (!a)
throw new IOException();
/// a is false means this field is wrong , the method need to be
/// terminated by FIleException
if (a)
throw new FIleException(“a is true”);
}
}
///
import java.io.IOException;
public class FIleException extends IOException {
public FIleException(String message) {
super(message);
}
}
可以在一个method里抛出多个异常,则此时再main里抛出异常会有三种方法;如果要抛出子类和父类的异常则只需要抛出父类的异常即可,这是因为多态的性质(多态,其实是一种downcasting,而upcasting则是危险的)