一、异常的概念
public class Test01 {
public static void main(String[] args) {
test2();
}
public static void test2(){
System.out.println("111");
try {
int a=1/0;
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("222");
}
}
package com.myproject;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test02 {
public static void main(String[] args) throws ParseException {
test1();
try {
test2();
} catch (ParseException e) {
e.printStackTrace();
}
test3();
System.out.println(test4());
}
//测试try-catch-finally
public static void test1(){
FileReader fr=null;
try {
fr=new FileReader("d:/a.txt");
System.out.println((char) fr.read());
System.out.println((char)fr.read());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fr!=null){
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//测试throws,声明式抛出
public static void test2() throws ParseException {
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String str="2009-10-1";
Date date=df.parse(str);
System.out.println(date);
}
/**
* "try-with-resource",可以自动关闭实现了Closable接口的类
* 编译器自动转换为try-catch-final
*/
public static void test3(){
try(FileReader fr=new FileReader("d:/a.txt")){
System.out.println((char) fr.read());
System.out.println((char)fr.read());
}catch (Exception e){
e.printStackTrace();
}
}
public static int test4(){
int n=10;
System.out.println("step1");
try {
System.out.println("step2");
n=20;
return n;
}catch (Exception e){
e.printStackTrace();
}finally {
n=40;
System.out.println("step3");
return n;
}
}
}
/**
* 测试自定义异常
*/
public class Test03 {
public static void main(String[] args) throws Exception {
Person p=new Person();
p.setAge(-20);
}
}
/**
* 不合法年龄异常
*/
class IllegalAgeException extends Exception{
//创建一个无参构造器
public IllegalAgeException() {
}
//创建一个带参构造器
public IllegalAgeException(String message){
super(message);
}
}
class Person{
private String name;
private int age;
public void setAge(int age) throws IllegalAgeException{
if(age<0){
throw new IllegalAgeException("人的年龄不能是负数");
}
this.age=age;
}
public int getAge(){
return age;
}
}