一、异常概述与异常体系结构
在使用计算机语言进行项目开发的过程中,即使程序员把代码写得尽善尽美,在系统的运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如:客户输入数据的格式,读取文件是否存在,网络是否始终保持通畅等等。
二、常见异常
常见异常:ArrayIndexOutOfBoundsException
常见异常:NullPointerException
常见异常:ArithmeticException
常见异常:ClassCastException
三、异常处理机制一:try-catch-finally
举例:
public class IndexOutExp {
public static void main(String[] args) {
String friends[] = { "lisa", "bily", "kessy" };
try {
for (int i = 0; i < 5; i++) {
System.out.println(friends[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("index err");
}
System.out.println("\nthis is the end");
}
}
程序IndexOutExp.java运行结果:java IndexOutExp
lisa
bily
kessy
index err
this is the end
public class DivideZero1 {
int x;
public static void main(String[] args) {
int y;
DivideZero1 c = new DivideZero1();
try {
y = 3 / c.x;
} catch (ArithmeticException e) {
System.out.println("divide by zero error!");
}
System.out.println("program ends ok!");
}
}
程序DivideZero1运行结果:java DivideZero1
divide by zero error!
program ends ok!
public class IOExp {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("atguigushk.txt");
int b; b = in.read();
while (b != -1) {
System.out.print((char) b);
b = in.read();
}
in.close();
} catch (IOException e) {
System.out.println(e);
} finally {
System.out.println(" It’s ok!");
}
}
}
四、异常处理机制二:throws
五、手动抛出异常
六、用户自定义异常类
public class MyExpTest {
public void regist(int num) throws MyException {
if (num < 0)
throw new MyException("人数为负值,不合理", 3);
else
System.out.println("登记人数" + num);
}
public void manager() {
try {
regist(100);
} catch (MyException e) {
System.out.print("登记失败,出错种类" + e.getId());
}
System.out.print("本次登记操作结束");
}
public static void main(String args[]) {
MyExpTest t = new MyExpTest();
t.manager();
}
}
一首小悟结束异常处理
世界上最遥远的距离,是我在if里你在else里,似乎一直相伴又永远分离;
世界上最痴心的等待,是我当case你是switch,或许永远都选不上自己;
世界上最真情的相依,是你在try我在catch。无论你发神马脾气,我都默
默承受,静静处理。到那时,再来期待我们的finally。
以上就是关于java中异常的介绍,如果有不当之处或者遇到什么问题,欢迎在文章下面留言~
如果你想了解更多关于Java的内容,可以查看:Java学习之路
转载请注明:https://blog.csdn.net/weixin_44662961/article/details/105670542