您的位置:首页 > 编程语言 > Java开发

Java的异常机制和包括异常体系

2019-03-17 22:31 162 查看

JAVA的异常机制及处理

Java的异常分为三种
Error错误:如AVTError,OutofMemoryError内存溢出错误。
RuntimeException运行时异常:如ClasscastException类型转换异常,NullpointerException空指针异常,ArithmeticException算术异常,IndexOutOfBoundsException索引越界异常等…
CheckedException可检查的异常:如IoException输入输出异常,SQLException数据库异常等…
其中错误是程序本身无法处理的,也不会对错误进行捕捉和抛出。
而Checked异常都是可以在编译阶段被处理的异常,所以它强制处理Checked异常,如果没有处理,则会编译错误,无法通过。
Java的异常处理主要就是声明异常、抛出异常和捕获异常。
异常处理的关键字:try、catch、throw、throws、finally。

声明异常:
public class W {

private static void Login() {
try {//可能产生的异常
int a=5;
int b=0;
System.out.println(a/b);
}
catch (Exception e) {//异常处理代码
System.out.println("处理");
}
finally {// 无论是否产生异常都会执行的代码
System.out.println("执行");
}
}
}

try块是必须的有的,如果没有try块,也就有后面的catch块和finally块;
catch块和finally块都是可以相互嵌套的,catch块和finally块至少出现其中之一,也可以同时出现。

public class W {

public static boolean test()
{
try
{
return false;
}
finally
{
return true;
}
}
public static void main(String[] args)
{
boolean asd = test();
System.out.println(asd);
}

}```

使用throw抛出异常
import java.io.FileNotFoundException;
public class W {

public static void main(String[] args) {
try {
a("c:/nihao.mp3");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public static String[] a(String name) throws FileNotFoundException{
return a(name);
}
public static String[] b(String name) throws FileNotFoundException {
return c(name);
}
public static String[] c(String name) throws FileNotFoundException{
RuntimeException e = new RuntimeException();
throw e;
}

}

当throw语句抛出的异常是RuntimeException异常,也可以完全不理会该异常,把该异常交给方法的调用者处理,可以一层一层往上面抛。
自定义异常
需要继承Exception,如果是RuntimeException,就应该继承该基类,定义异常类时通常需要提供两种构造器:1,无参的构造器,2,带字符串的构造器,这个字符串作为异常对象的getMessage方法返回值,调用super将字符串参数传给异常对象的message属性,message属性就是异常对象的详细描述信息。

public class Map extends RuntimeException {

public String username;
public double possword;

public Map() {

}

public Map(String string) {
super();
}
}
总结:try、catch和finally都不能单独使用,只能是try-catch、try-finally或者try-catch-finally。
try语句块监控代码,出现异常就停止执行下面的代码,然后将异常移交给catch语句块来处理。
finally语句块中的代码一定会被执行 。
throws:声明一个异常,throw 抛出一个异常。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: