Error: Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。一般不编写针对性的代码进行处理。Exception:其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。
Exception可以分为编译时异常和运行时异常。
二运行时异常RuntimeException
运行时异常:是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常。java.lang.RuntimeException类及它的子类都是运行时异常。
常见的运行时异常有:数组下标越界异常,算术异常,类型转换异常,空指针异常。
//1.数组下标越界的异常:ArrayIndexOutOfBoundsException
public void test2(){
int[] i = new int[10];
System.out.println(i[10]);
}
//2.算术异常:ArithmeticException
public void test3(){
int i = 10;
System.out.println(i / 0);
}
//3.类型转换异常:ClassCastException
public void test4(){
Object obj = new Date();
String str = (String)obj;
}
//4.空指针异常:NullPointerExcetion
public void test5(){
String str = new String("AA");
str = null;
System.out.println(str.length());
}
三异常处理
由虚拟机自动生成:程序运行过程中,虚拟机检测到程序发生了问题,如果在当前代码中没有找到相应的处理程序,就会在后台自动创建一个对应异常类的实例对象并抛出——自动抛出。由开发人员手动创建:Exceptionexception =new ClassCastException();——创建好的异常对象不抛出对程序没有任何影响,和创建一个普通对象一样
异常处理方式一try-catch-finally
try{
...... //可能产生异常的代码
}
catch( ExceptionName1 e ){
...... //当产生ExceptionName1型异常时的处置措施
}
catch( ExceptionName2 e ){
...... //当产生ExceptionName2型异常时的处置措施
}
finally{
...... //无论是否发生异常,都无条件执行的语句,一般用来关闭资源
}
public class TestException1 {
public void test6() {
FileInputStream fis = null;
try {
fis = new FileInputStream(new File("hello.txt"));
int b;
while ((b = fis.read()) != -1) {
System.out.print((char) b);
}
} catch (FileNotFoundException e1) {
System.out.println("文件找不到了!");
} catch (IOException e1) {
System.out.println(e1.getMessage());
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
异常处理方式二—throws
public class TestException {
public static void main(String[] args){
try{
method2();
}catch(FileNotFoundException e){
System.out.println(e.getMessage());
}catch(IOException e){
e.printStackTrace();
}
method3();
}
public static void method3(){
try{
method1();
}catch(Exception e){
e.printStackTrace();
}
}
public static void method2() throws FileNotFoundException,IOException{
method1();
}
public static void method1() throws FileNotFoundException,IOException{
FileInputStream fis = new FileInputStream(new File("hello1.txt"));
int b;
while((b = fis.read()) != -1){
System.out.print((char)b);
}
fis.close();
}
}
Class DemoException extends Exception
{
DemoException(String message)
{
super(message);
}
}
通过throw将自定义异常抛出。