异常exception
中断程序
处理异常==排错
1:搜索ArithmeticException 非受检unchecked 编译时没有错
2:大量输出语句验证 缩小代码范围,寻找错误点
3:会用注释 不断找到对的代码,进而发现错误的代码段
4:打印日志 错误信息log4j 第三方类库
/**
*
*/
package com.zhiyou.S;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.FileAlreadyExistsException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Administrator
*
*/
public class ExceptionClassTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// exception 异常
// 发现异常 处理异常
// 1:有呢些异常
// ArithmeticException 算数异常
// System.out.println(100/0);
// ArrayIndexOutOfBoundsException数组越界异常
// int[] array = new int[0];
// System.out.println(array[1]);
// NullPointerException空指针(对象)异常
// String string = null;
// System.out.println(string.length());
// error
// OutOfMemoryError:
// Requested array size exceeds VM limit
// int[] arr = new int[1024*1024*1024];
// System.out.println(arr);
// 2:异常的API
// exception 继承与throwable
// Error 继承与throwable
// 通常所说的异常指的是exception
// 对于exception分类
// 3.1受检 check 编译都会出现,要求程序员必须处理
// 3.2非受检 unchecked 编译不会出现,运行时异常 runtimeException
// 程序员,会对非受检的异常提前预知,会通过语句进行处理,try catch
// FileNotFoundException 受检异常 必须处理
// FileInputStream inputStream = new FileAlreadyExistsException("");
// 4:处理
// 受检异常必须处理,不处理,代码不能编译
// 非受检异常 处理方法
// 1:类似if语句提前进行绕开异常
// 2:官方的try..catch
// --------------------------------------------------------------------
int a=1;
int b=0;
int c=0;
if (b==0) {
System.out.println("除数不能为0");
}else {
c=a/b;
}
System.out.println(c);
// try 尝试 可能出现异常的代码放在try中
// catch 捕获 捕获try可能存在的异常
try {
int value=1/0;
String string = null;
System.out.println(string.length());
// 捕获算数异常
} catch (ArithmeticException e) {
// TODO: handle exception
// 都是输出异常信息的
// 异常信息说明
System.out.println(e.getMessage());
// 异常原因
System.out.println(e.getCause());
// 打印异常在栈中的追踪信息
e.printStackTrace();
// 注意:异常会显示在呢一行出现异常
// 捕获空对象异常
}catch (NullPointerException e) {
// TODO: handle exception
// System.out.println(e.getMessage());
e.printStackTrace();
}finally {
System.out.println("finally里面的代码总会执行");
}
// 总结:如果想测试多条语句,可以使用多个try...catch
// 语句,而且多个try..catch是可以合并成一个的,如果较少
// try..catch数量。但是对于try中代码,每次之后响应一个catch
// catch中exception e对象是所有exception的父类。
// ---------------------------------------------------------------------
// 3:抛出异常 throw throws 并没有进行处理
// throws在方法定义时抛出可能在方法执行要抛出的异常
// throw抛出的是异常对象
// 如果是受检异常,即便调用的方法有throws,但是执行这个方法仍旧需要执行这个异常
// expMethod();
expMethod2();
expMethod3();
}
// public static void expMethod() throws FileNotFoundException{
//
// // FileInputStream inputStream = new FileInputStream("D:\\Downloads");
// }
public static void expMethod2() throws ArithmeticException{
int c=1/0;
}
public static void expMethod3() {
int a = 1;
int b = 0;
int c = 0;
if (b == 0) {
throw new ArithmeticException("除数不能为0");
}else {
c = a / b;
}
}
}