Java异常处理总结
文章目录
- 一. 异常概述
- 1.1 异常定义
- 1.2 异常体系结构
- 二.常见异常
- 三.异常处理机制 try catch
- 四. 异常处理机制 try catch
- finally
- 五. 异常处理机制 throws
- 5.2 选择try catch or throws
- 六. 手动抛出异常 throw
- 七. 用户自定义异常类
- 八. 异常练习
- 九. 总结
- 常见异常类型
- 1 NULLPointerException
- 2 ArrayIndexOutOfBoundsException
- 3 ClassCastException
- 4 NUmberFormatException
- 5 InputMismatchException
- 6 ArithmeticException
一. 异常概述
输入数据格式
文件是否存在
网络稳定问题
1.1 异常定义
异常:程序中发生的不正常情况
异常分为两类
Error
JVM无法解决的严重问题:JVM内部错误、资源耗尽
比如:StackOverflowError 、 OOM
一般不编写针对性的代码进行处理public class ErrorTest {
public static void main(String[] args) {
//TODO 1 StackOverflowError 无限递归
main(args);
//TODO 2 java.lang.OutOfMemoryError 堆溢出
Integer[] arr = new Integer[1024 * 1024 * 1024];
}
}
Execption
因编程错误 or 偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理,例如:- 空指针
- 读取不存在文件
- 网络中断
- 数组角标越界
两种解决方法
1 . 遇到错误就i终止
2 . 编写就考虑异常的情况,错误检测 错误消息提示 处理
捕获异常理想是在 编译期间(编译时异常),但有的错误只有在运行时间才会发生(运行时异常)
1.2 异常体系结构
编译的时候不会检查 非受检异常
二.常见异常
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Scanner;
public class ExceptionTest {
/*
* |-----编译时间异常(Checked)
* 在编译时就会报错,不会生成字节码文件
* */
//TODO FileNotFoundException
@Test
public void test7(){
File file = new File("hello.txt");
FileInputStream fileInputStream = new FileInputStream(file);
int data = fileInputStream.read();
while(data != -1){
System.out.println((char)data);
data = fileInputStream.read();
}
fileInputStream.close();
}
/*
* |-----运行时间异常(unChecked / runtimeException)
* */
//TODO 1 NUllPointerException
@Test
public void test1(){
// int[] arr = null;
// System.out.println(arr[3]);
// String str = "abc";
// str = null;
// System.out.println(str.charAt(0));
}
//TODO 2 ArrayIndexOutOfBoundsExcption
@Test
public void test2(){
int arr[] = new int[10];
System.out.println(arr[10]);
String str = "abc";
System.out.println(str.charAt(3));
}
//TODO 3 ClassCastException
@Test
public void test3(){
Object obj = new Date();
String str = (String)obj;
}
//TODO 4 NumberFormatException
@Test
public void test4(){
String str = "123";
str = "abc";
int num = Integer.parseInt(str);
}
//TODO 5 InputMismatchException
@Test
public void test5(){
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
System.out.println(s);//输入一个String
}
//TODO 6 ArithmeticException
@Test
public void test6(){
int a = 2;
int b = 0;
System.out.println(a / b);
}
}
三.异常处理机制 try catch
在编写程序时,经常要在可能出现错误的地方加上检测的代码,如进行x/y运算时,要检测分母为0,数据为空,输入的不是数据而是字符等。过多的if-else分支会导致程序的代码加长、臃肿,可读性差。因此采用异常处理机制。
Java异常处理
Java采用异常处理机制,将异常处理的程序代码集中在一起,与正常程序分开,使得程序简介、优雅、易于维护
1) try catch
2) throws + 异常类型
四. 异常处理机制 try catch
异常处理 :抓抛模型
过程1 抛出
一旦出现异常,就会在异常code处生成一个对应异常类的对象,并将其抛出
一旦抛出异常,其后的code将不再执行
过程2 抓
可以理解为异常的处理方式
- try catch finally 的使用
throws
try{
//可能出现异常的code
}catch(异常类型1 变量名1){
//处理异常的方式1
}catch(异常类型2 变量名2){
//处理异常的方式2
}…
finally{//一定会执行的code
}
Catch规范
catch异常类型都是平行关系 那么谁先谁后都一样 平行关系
cath异常类型如果满足子父类关系,则应该把子类放到前面,否则出错
异常处理的方式
- String getMessage()
- printStackTrace()
在try中声明的变量
在出了Try括号之后 ,将不再有效
finally
finally是可选的
@Test
public void testMethd(){
int num = method();
System.out.println(num);
}
public int method(){
try{
int arr[] = new int[10];
System.out.println(arr[10]);
return 1;
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
return 2;
}finally {
System.out.println("finally一定指定,其他不一定");
return 3;
}
}
五. 异常处理机制 throws
处理方式二:throws + 异常类型
写在方法声明处,执行此方法时,可能会抛出异常
一旦当方法执行时,出现异常,仍会在异常代码处生成一个异常对象,此对象满足throws后异常类型,就会被抛出
异常代码后续的代码就不再执行!
5.2 选择try catch or throws
- 如果父类中被重写的方法没有throws方式处理,子类也不能throws , 必须try catch
- 执行的方法A中 先后调用了另外的几个 递进关系的方法 , 递进关系的方法 建议用throws方式,执行的方法A建议用try catch处理
六. 手动抛出异常 throw
关于异常对象的产生
- 系统自动产生的异常
手动生成的异常对象 并抛出 (throw)
package com.JavaBase.tarin.d016;
public class StudentTest{
public static void main(String[] args) {
Student s = new Student();
try {
s.regist(-1001);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
class Student {
private int id;
public void regist(int id) throws Exception {
if(id > 0){
this.id = id;
}else {
// System.out.println("输入非法");
//TODO 手动抛出异常对象
// throw new RuntimeException("输入对象异常!");
throw new Exception("输入对象异常!");
}
}
}
七. 用户自定义异常类
- 继承现有异常结构RuntimeException Exception
- 提供一个全局常量serialVersionUID 序列号 ,对类的一个标识
提供重载的构造器
public class MyException extends RuntimeException{
static final long serialVersionUID = -7034897190745766939L;
public MyException(){
}
public MyException(String msg){
super(msg);
}
}
八. 异常练习
编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算
两数相除。
对 数 据 类 型 不 一 致 (NumberFormatException) 、 缺 少 命 令 行 参 数
(ArrayIndexOutOfBoundsException、
除0(ArithmeticException)及输入负数(EcDef 自定义的异常)进行异常处理。
(1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
(2)在main()方法中使用异常处理语句进行异常处理。
(3)在程序中,自定义对应输入负数的异常类(EcDef)。
(4)运行时接受参数 java EcmDef 20 10 //args[0]=“20” args[1]=“10”
(5)Interger类的static方法parseInt(String s)将s转换成对应的int值。
如:int a=Interger.parseInt(“314”); //a=314;
package com.JavaBase.tarin.d016;
/*
* 编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算
两数相除。
对 数 据 类 型 不 一 致 (NumberFormatException) 、 缺 少 命 令 行 参 数
(ArrayIndexOutOfBoundsException、
除0(ArithmeticException)及输入负数(EcDef 自定义的异常)进行异常处理。
(1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
(2)在main()方法中使用异常处理语句进行异常处理。
(3)在程序中,自定义对应输入负数的异常类(EcDef)。
(4)运行时接受参数 java EcmDef 20 10 //args[0]=“20” args[1]=“10”
(5)Interger类的static方法parseInt(String s)将s转换成对应的int值。
如:int a=Interger.parseInt(“314”); //a=314;
*
* */
public class EcmDev {
public static void main(String[] args) {
try{
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int result = ecm(i,j);
}catch (NumberFormatException e){
// e.printStackTrace();
System.out.println("数据类型不一致");
}catch (ArrayIndexOutOfBoundsException e){
// e.printStackTrace();
System.out.println("缺少命令行参数");
}catch (ArithmeticException e){
// e.printStackTrace();
System.out.println("除0");
}catch (EcDef e){
e.printStackTrace();
}
}
public static int ecm(int i ,int j) throws EcDef{
if(i < 0 || j < 0){
throw new EcDef("分子或分母为负数");
}
return i / j;
}
}
九. 总结
常见异常类型
1 NULLPointerException
空指针异常
//TODO 1 NUllPointerException
@Test
public void test1(){
// int[] arr = null;
// System.out.println(arr[3]);
// String str = "abc";
// str = null;
// System.out.println(str.charAt(0));
}
2 ArrayIndexOutOfBoundsException
数组下标越界异常
public void test2(){
int arr[] = new int[10];
System.out.println(arr[10]);
String str = "abc";
System.out.println(str.charAt(3));
}
3 ClassCastException
类强制转换异常
public void test3(){
Object obj = new Date();
String str = (String)obj;
}
4 NUmberFormatException
数值格式化异常
//TODO 4 NumberFormatException
@Test
public void test4(){
String str = "123";
str = "abc";
int num = Integer.parseInt(str);
}
5 InputMismatchException
输入不匹配 异常
@Test
public void test5(){
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
System.out.println(s);//输入一个String
}
6 ArithmeticException
算数异常
@Test
public void test6(){
int a = 2;
int b = 0;
System.out.println(a / b);
}
还没有评论,来说两句吧...