版权声明:尊重原创,码字不易,转载需博主同意。 https://blog.csdn.net/qq_34626097/article/details/83551925
java之程序的异常体系结构
1. 程序中的异常
- 不可避免的异常,在系统的运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如:客户输入数据的格式,读取文件是否存在,网络是否始终保持通畅等等
- 异常:在Java语言中,将程序执行中发生的不正常情况称为“异常”。(开发过程中的语法错误和逻辑错误不是异常)
- 对于这些错误,一般有两种解决方法:一是遇到错误就终止程序的运行。另一种方法是由程序员在编写程序时,就考虑到错误的检测、错误消息的提示,以及错误的处理。
2. java异常层次体系结构图
3. java异常的体系结构,实习面试点
- java.lang.Throwable
1.1. Error:错误,程序中不进行处理(通常是jar导入不全,或者jdk版本,路径等问题)
1.2. Exception:异常,要求在编写程序时,就要考虑到对这些异常的处理 - Exception:异常
2.1. 编译时异常:在编译期间会出现的异常(执行javac.exe命令 时,出现异常) ,且IO异常通常需要显示处理。
2.2运行时异常:在运行期间出现的异常(执行java.exe命令时,出现异常),通常为程序员考虑不周,而出现的异常。
注:当执行一个程序时,如果出现异常,那么异常之后的代码就不再执行!
java异常代码体会
public class TestException {
//编译时异常
@Test
public void test6(){
// FileInputStream fis = new FileInputStream(new File("hello.txt"));
// int b;
// while((b = fis.read()) != -1){
// System.out.println((char)b);
// }
// fis.close();
}
//常见的运行时异常
/*
* Bank bank = new Bank();
* Customer[] customers = new Customer[5];
* customers[0] = new Customer();
* System.out.println(customers[0].getFirstName());可能出现空指针异常
* customers[0].setAccount(new Account(200));
* customers[0].getAccount().withdraw(100);可能出现空指针异常
*/
//4.空指针异常:NullPointerExcetion
@Test
public void test5(){
// Person p = new Person();
// p = null;
// System.out.println(p.toString());
String str = new String("AA");
str = null;
System.out.println(str.length());
}
//3.类型转换异常:ClassCastException
@Test
public void test4(){
Object obj = new Date();
String str = (String)obj;
//String str1 = (String)new Date();
}
//2.算术异常:ArithmeticException
@Test
public void test3(){
int i = 10;
System.out.println(i / 0);
}
//1.数组下标越界的异常:ArrayIndexOutOfBoundsException
@Test
public void test2(){
int[] i = new int[10];
//System.out.println(i[10]);
System.out.println(i[-10]);
}
@Test
public void test1(){
Scanner s = new Scanner(System.in);
int i = s.nextInt();
System.out.println(i);
}
}
class Person{
}