- java异常捕获机制中的try-catch,try块是用来扩上可能出错的代码片段,catch块是用来捕获try块中代码抛出的错误,并解决。
public static void main(String[] args) {
System.out.println("程序开始了");
try{
String str="";
System.out.println(str.length());
System.out.println(str.charAt(0));
System.out.println(Integer.parseInt(str));
}catch(NullPointerException e){
System.out.println("出现了空指针");
}catch(StringIndexOutOfBoundsException e){
System.out.println("字符串下标越界了");
}catch(Exception e){
System.out.println("反正就是出了个错");
}
System.out.println("程序结束了");
}
- finally块,finally块定义在异常捕获机制的最后,可以直接跟在try块之后或者最后一个catch之后。finally块中的代码一定执行,无论try块中的代码是否抛出异常,所以通常会把释放资源等操作放在finally中,例如关闭流。
public static void main(String[] args) {
System.out.println("程序开始了");
try {
String str="";
System.out.println(str.length());
} catch (Exception e) {
System.out.println("出错了");
}finally{
System.out.println("finally中的代码执行了");
}
System.out.println("程序结束了");
}
- finally对于流的处理
public static void main(String[] args) {
BufferedReader br=null;
try {
br=new BufferedReader(new InputStreamReader(new FileInputStream("src/day08/ExceptionDemo3.java")));
String line=null;
while((line=br.readLine())!=null){
System.out.println(line);
}
} catch (Exception e) {
System.out.println("出错了");
}finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
}
}
}
}
- 测试异常的抛出
public class Person {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) throws IllegalAgeException{
if(age<0||age>100){
throw new IllegalAgeException("年龄不合法");
}
this.age = age;
}
}
public static void main(String[] args) {
Person p=new Person();
try {
p.setAge(200);
} catch (IllegalAgeException e) {
e.printStackTrace();
}
System.out.println("年龄为:"+p.getAge());
}
- 重写父类一个含有throws异常抛出声明的方法时,子类该方法的throws的重写原则
public class ExceptionDemo5 {
public void dosome() throws IOException,AWTException{
}
}
class Son extends ExceptionDemo5{
}
- Exception常用方法
public static void main(String[] args) {
System.out.println("程序开始了");
try{
String str="abc";
System.out.println(Integer.parseInt(str));
}catch(Exception e){
System.out.println(e.getMessage());
}
System.out.println("程序结束了");
}
- 自定义异常,通常是用来描述 某个业务逻辑上出现的问题。自定义异常的名字应当做到见名知义.
年龄不合法异常
public class IllegalAgeException extends Exception{
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
}
public IllegalAgeException() {
super();
}
public IllegalAgeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public IllegalAgeException(String message, Throwable cause) {
super(message, cause);
}
public IllegalAgeException(String message) {
super(message);
}
public IllegalAgeException(Throwable cause) {
super(cause);
}
}