package lesson05;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class ExceptionTest {
public static void main(String[] args) {
//1.Error
// byte[] b = new byte [1024*1024*60];
// main(new String[0]);
//2.异常
//1.程序执行到了出异常的位置
//2.虚拟机JVM检测到数学异常
//3.虚拟机在后台帮我们创建了ArithmeticException类的对象
//4.将异常对象抛出
//5.程序停止执行,打印异常现象
//testExceptionObj();
//testThrows();
//testCatch();
testMyOwnException();
// int[] arr = new int[10];
// System.out.println(arr[10]);//运行时异常:数组下标越界异常
}
public static void testExceptionObj () {
int a = 10;
int b = 0;
int c = a/b;
System.out.println("c="+ c);//运行时异常:数学异常
}
public static void testThrows() throws FileNotFoundException{
InputStream in = new FileInputStream("aa.txt");//非运行时异常(编译时异常):找不到文件
}
public static String testCatch(){
//注意:前面的catch块捕获的异常不能覆盖后面catch块中捕获异常
try{
//在try块中,检测尝试执行的代码
int i = 10/2;
//InputStream in = new FileInputStream("aa.txt");
System.out.println("try");
return "hello";
//多异常捕获,可以使用
}
// catch (FileNotFoundException e){
// //在catch块中执行捕获异常后所要执行的代码,通常为处理异常的相应措施
// System.out.println("FileNotFoundException");
// }
catch(ArithmeticException e){
System.out.println("数学异常");
}
catch(Exception e){
System.out.println("这里是用Exception捕获的");
}finally{
System.out.println("这里是必执行finally块");//1.不管try。。。catch走了哪一支,finally块里的语句都会被强制执行
//2.即使是在return后面,finally块也还是会执行
}
//异常捕获后,程序可以继续执行
System.out.println("程序继续执行了");
return "end";
}
public static void testMyOwnException(){
MyOwnException e = new MyOwnException();
throw e;
}
}
package lesson05;
public class MyOwnException extends RuntimeException{
private static final long serialVersionUID = 1L;
}