public class ExceptionDemo02 {
//模拟文件读取 自定义的异常
public static void main(String[] args) {
//写一个方法去读一个文件
String str;
try {
str = readTxt("H:\\a.txt");
System.out.println(str);
} catch (PathNotFoundException e) {
System.out.println("异常被处理了");
System.out.println(e.getMessage());
}catch(FileFormatException e){
System.out.println("异常又被处理了");
}
System.out.println("程序继续执行");
}
//path代表文件的地址
public static String readTxt(String path) throws PathNotFoundException, FileFormatException{
//判断路经地址是否合法
if(path.startsWith("H:")){
throw new PathNotFoundException("文件路经不对,请重写");//没有这个异常,那么需要自己创建
}
if(path.endsWith(".txt")){
throw new FileFormatException();
}
return "文件读取成功了 ";
}
}
class PathNotFoundException extends Exception{
private String message;
public PathNotFoundException(){
}
public PathNotFoundException(String message){
this.message =message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
class FileFormatException extends Exception{
public FileFormatException(){
}
public FileFormatException(String message ){
super(message); //父类的方法的值
}
}
finally举例
public class FinallyDemo02 {
public static void main(String[] args) {
System.out.println(demo02());
}
public static String demo02(){
String str;
try{
str = "abc";
return str;
}finally{
str = "rty";
}
}
public static Person demo01(){
Person p = new Person();
try{
// p的地址是 0x1111
// 给p赋值
p.setName("张无忌");
p.setAge(20);
// 遇到return p 挂起
return p;
}finally{
p = new Person();
// 继续给p的属性赋值
p.setName("杨过");
p.setAge(36);
}
}
}
class Person{
private String name;// 姓名
private int age;// 年龄
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}