try catch处理异常
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ExceptionTest01 {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
FileReader reader = null;
try {
reader = new FileReader("d:/a.txt");
char c = (char) reader.read();
System.out.println(c);
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
}finally {
System.out.println("最后一步");
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
throws抛异常
import java.io.FileReader;
import java.io.IOException;
public class ExceptionTest02 {
public static void main(String[] args) throws IOException {
readFile();
}
public static void readFile() throws IOException {
FileReader reader = new FileReader("c:/a.txt");
char c = (char) reader.read();
System.out.println(c);
}
}
自定义异常(其实就是定义异常提示信息)
利用异常处理机制的方法来制作一个代码程序段。输入“I am 007”时,打印“亲爱的007,您好”;输入其他字符串时,打印“对不起,请下次进入”,然后程序结束。
import java.util.Scanner;
public class ExceptionTestTest03 {
public static void main(String[] args) throws StrException {
String str = null;
PrintStr p = new PrintStr(str);
}
}
class PrintStr{
public PrintStr(){}
public PrintStr(String str) throws StrException{
Scanner sc = new Scanner(System.in);
System.out.println("请输入一条字符串");
str = sc.nextLine();
sc.close();
if(str.equals("I am 007")){
System.out.println("亲爱的007,您好");
}else{
throw new StrException("对不起,请下次进入");
}
}
}
class StrException extends Exception{
public StrException(){}
public StrException(String msg){
super(msg);
}
}