Java采用面向对象的方式处理异常

是程序无法处理的错误,较严重。
Error发生时,Java虚拟机一般会选择线程终止。
是程序本身能够处理的异常。
这里异常通常是由编程错误导致,因此可以用逻辑处理来避免异常。
这类异常在编译时就必须作出处理,否则无法通过编译。
try-catch-finally
\uFFFF表示空字符System.out.printf不能输出charfinally中用来关闭程序块已打开的资源,例如关闭文件流,释放数据库连接等。public class IoException {
public static void main(String[] args) {
FileReader fileReader = null;
try {
fileReader = new FileReader("input/input.txt");
char ch = (char)fileReader.read();
while (ch != '\uFFFF') {
System.out.printf("" + ch);
ch = (char)fileReader.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileReader != null)
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
readFile抛出异常,main捕获到异常,并输出自定义语句。
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Throws {
public static void main(String[] args) {
try {
readFile("input/input.txt");
} catch (FileNotFoundException e) {
System.out.println("所需文件不存在!");
} catch (IOException e) {
System.out.println("文件读写错误!");
}
}
public static void readFile(String fileName) throws FileNotFoundException, IOException {
FileReader fileReader = new FileReader(fileName);
char ch = (char)fileReader.read();
while (ch != '\uFFFF') {
System.out.printf("" + ch);
ch = (char)fileReader.read();
}
fileReader.close();
}
}
public class IllegalAgeException extends Exception{
IllegalAgeException() {}
IllegalAgeException(String message) {
super(message); // 调用父类的构造函数
}
}

public class Person {
private String name;
private int age;
public void setName(String name) {this.name = name;};
public void setAge(int age) throws IllegalAgeException {
if (age < 0) {
throw new IllegalAgeException("年龄不能为负数");
}
this.age = age;
};
public static void main(String[] args) {
Person person = new Person();
person.setName("张三");
try {
person.setAge(-24);
} catch (Exception e){
e.printStackTrace();
} finally {
System.out.println("exit");
}
}
}
