测试异常1:异常的基本用法
package TestException;
import java.io.File;
import java.io.FileNotFoundException;
/**
* 测试一下Exception的使用
* @author Wang
*
*/
public class testException {
public static void main(String[] args) {
//int i = 1/0; 在这里汇报一个这样的异常:不需要我们捕获;属于uncheck异常Exception in thread "main" java.lang.ArithmeticException: / by zero
//at TestException.testException.main(testException.java:10)
//Computer c = null; 像这样的uncheck的异常我们通常都会加一个if语句来限制一下 如下程序
//c.start(); 这个会报Exception in thread "main" java.lang.NullPointerException 空指针的异常;
// Computer c = null;
// if(c!=null){
// c.start(); //对象是null,调用了对象方法或属性!
// }
//String str = "123abc";//像这样的uncheck异常都是可以编译过去的但是checked异常就需要我们去捕获
//Integer i = new Integer(str);这里汇报这个异常:格式异常他只能转化整数类型的 java.lang.NumberFormatException:
//Thread.sleep(3000);//这个是让程序睡眠三秒钟属于checked异常需要我们去捕获或者去抛出
try {//捕获这个异常 其实是因为他的源码再定义的时候写了抛出异常
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("aaa");//这个finally里面的语句不论有没有异常都会打印出来的
}
File f = new File("c:/Hello.txt");
if(!f.exists()) {
try {
throw new FileNotFoundException("File cannot be found");//throw 这个是手动抛出异常
}catch(FileNotFoundException e) {//catch语句try里面一旦遇到异常就会执行这里面的语句 执行玩这里面的以后不会在回去执行try里面的语句了;
e.printStackTrace();
}finally {
System.out.println("aaa");//这个finally里面的语句不论有没有异常都会打印出来的
}
}
}
}
class Computer{
void start() {
System.out.println("计算机启动");
}
}
测试异常2:File的异常
package TestException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* 测试File类的一些异常
* @author Wang
*
*/
public class testFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String str;
str = new testFile().openFile();
System.out.println(str);
}
String openFile() throws FileNotFoundException,IOException { //抛出两个异常 抛出之后就是谁调用 谁就处理这个异常 或者继续向上抛出 但是总是要有处理的 都不处理就是虚拟机来处理
FileReader reader = new FileReader("d:/a.txt");
char c = (char)reader.read();//每次读一个字符;
//System.out.println(c);
return ""+c;
}
}
测试异常3:异常的继承机制
package TestException;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* 测试异常抛出的范围
* @author Wang
*
*/
public class testRange {
class A {
public void method() throws IOException { }
}
class B extends A { public void method() throws FileNotFoundException { }
}
class C extends A { public void method() { }
}
// class D extends A { public void method() throws Exception { } //超过父类异常的范围,会报错!
// }
class E extends A { public void method() throws IOException, FileNotFoundException { }
}
class F extends A { public void method() throws IOException, ArithmeticException { }
}
// class G extends A { public void method() throws IOException, ParseException { }
// }
}
注意:
子类抛出的异常范围不能超过父类的异常范围: