JAVA异常处理
异常概述
- 在JAVA语言中,将程序中发生的不正常情况称之为异常
- 异常分类
- Error:JAVA虚拟机无法处理的严重问题,如JVM系统内部错误,资源耗尽等,一般不编写对应代码进行处理
- Exception:因编程错误或者一些偶然因素造成的问题,可以使用针对性代码进行处理
- 空指针访问
- 试图读取不存在的文件
- 网络连接中断
- 数组角标超界
异常处理
抓抛模型
- 抛:程序正常执行中,一旦出现异常就会在代码异常处生成一个对应异常类的对象,并将对象抛出,抛出后后面代码不再执行
- 抓:可以理解为异常处理方式
try-cathc-finaly
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TryCathc {
public static void main(String[] args) {
FileInputStream fis=null;
try {
File file=new File("hello.txt");
fis=new FileInputStream(file);
int data=fis.read();
while (data!=1){
System.out.println((char) data);
data= fis.read();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if(fis!=null){
fis.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
throws + 异常类型
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Throws {
public static void main(String[] args) {
try {
test2();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void test2() throws IOException{
test1();
}
public static void test1() throws FileNotFoundException,IOException{
File file=new File("hello.txt");
FileInputStream fis=new FileInputStream(file);
int data=fis.read();
while (data!=1){
System.out.println((char) data);
data= fis.read();
}
fis.close();
}
}
手动抛出异常
- 可以用现有的异常类
- 也可以自己定义异常类抛出
public class StudentThrow {
public static void main(String[] args) {
try {
Studen s=new Studen();
s.regist(-1);
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Studen{
private int id;
public void regist (int id) throws Exception{
if(id>0){
this.id=id;
}else {
throw new MyException("输入有误");
}
}
public String toString(){
return "id为"+this.id;
}
}
public class MyException extends RuntimeException{
static final long serialVersionUID=-723L;
public MyException(){
}
public MyException(String msg){
super(msg);
}
}
示例
public class EcmDef {
public static void main(String[] args) {
try {
int i=Integer.parseInt(args[0]);
int j=Integer.parseInt(args[1]);
int result=ecm(i,j);
System.out.println(result);
} catch (NumberFormatException e){
System.out.println("数据类型不一致");
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("缺少命令行参数");
}catch (ArithmeticException e){
System.out.println("除0");
} catch (EcDef e) {
System.out.println(e.getMessage());
}
}
public static int ecm(int i,int j) throws EcDef{
if(i<0||j<0){
throw new EcDef("分子或分母为负数");
}
return i/j;
}
}
class EcDef extends Exception{
EcDef(){
}
EcDef(String msg){
super(msg);
}
}