`
CrazyMizzz
  • 浏览: 23283 次
  • 性别: Icon_minigender_1
  • 来自: 浙江
社区版块
存档分类
最新评论

java异常处理机制

阅读更多
java异常关键字有以下几个,分别为 try catch final throw throws
他们的定义分别为
try:    Opening exception-handling statement.
catch:  Captures the exception.
finally: Runs its code before terminating the program.
throws:  Lists the exceptions a method could throw.
Throw:   Transfers control of the method to the exception handler

java异常关键字的作用
try{}:try语句块
捕捉异常,会把有可能发生异常的代码写在try语句块中,
在执行过程中,如果代码发生异常,try语句块会捕捉异常,转交给
catch语句进行处理
catch(异常类型 对象名){}:
catch语句会根据try语句块捕捉异常的进行匹配,执行相应的
处理代码。
finally{}
不管是否发生异常都会执行的语句块;
用来释放一些必须要释放的资源。
throw
在方法里边向外抛出异常,需要使用throws或者try{}catch进行
处理操作。
可以使用throw创建一个新异常对象。
throws
throws是将异常抛给调用的地方。

2.Java中异常的分类
Throwable
Error:错误
错误一般是代码上无法进行修改的异常
Exception :异常
运行时异常:RuntimeException
NullPointerException
ArrayIndexOutOfBoundsException

强制异常
IOException
ClassNotFoundException
SocketException

对异常进行测试

public class Demo {

private static Demo d;

private static int[] array = new int[10];

public static void main(String[] args) {
try {
byZero();
}catch (Exception e) {
e.printStackTrace();//打印异常的堆栈信息
}

try {
nullMethod();
} catch (Exception e) {
e.printStackTrace();
}

try {
indexMethod();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void byZero() throws Exception {
try {
int i = 10 / 0;
} catch (ArithmeticException e) {
// throw new ArithmeticException("除数为0");
throw new Exception("除数为0");
}
}

public static void nullMethod() throws Exception {
try {
d.hashCode();
} catch (NullPointerException e) {
throw new Exception("空指针异常");
}
}

public static void indexMethod() throws Exception {
try {
array[-1] = 0;
} catch (ArrayIndexOutOfBoundsException e) {
throw new Exception("数组越界");
}
}

}
java异常机制的作用

1.可以在不终止程序的情况下找到错误并分析
2.把错误信息扔出来处理


如果发生异常,如何进行处理?
1.找是什么类型的异常
2.找异常发生的哪一个行代码(是我们编写的类)
3.在这行代码前加上输出测试语句,测试信息是否正确
4.找到调用方法的哪一行代码,在代码前输出测试语句


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics