您的位置:首页 > 运维架构 > 网站架构

java异常机制:异常架构,执行流程,throw/throws的区别,自定义异常

2018-03-15 11:18 746 查看

1.异常机制的原因:

程序的常见错误:如用户输入错误,设备错误,硬盘错误等。



2.Exception:

java提供的用来处理程序错误的机制,如1/0等

3.异常处理流程:



4.分类:



5.try-catch-finally-return执行顺序:

public class ExceptionTest {

/**
* @param args
*/
public static void main(String[] args) {
String s = out();
System.out.println(s);
System.out.println("main");
}

public static String out(){
try {
System.out.println("try-正常代码");
int i = 1/0;//发生异常处;
System.out.println("try-异常之后的代码");
return "return -try";
} catch (Exception e) {
System.out.println("catch");
return "return -catch";
} finally{
System.out.println("finally");
return "return-finally";
}
}

}

try正常代码----try抛出异常----catch中return之前代码----finally中代码-----catch中return执行-----继续往下执行





6.throw throws区别

throw是语句抛出一个异常,一般是在代码块的内部,当程序出现某种逻辑错误时由程序员主动抛出某种特定类型的异常;

        如ssm架构事务中常用的:throw new RuntimeException();

        相当于RuntimeExcetpion,在调用时不需要try-catch

throws是方法可能抛出异常的声明。(用在声明方法时,表示该方法可能要抛出异常)

当某个方法可能会抛出某种异常时用于throws 声明可能抛出的异常,然后交给上层调用它的方法程序处理
        相当于checkedException,需程序在调用处添加try-catch处理
public static void main(String[] args) {
String s = "abc";
if(s.equals("abc")) {
throw new NumberFormatException();
} else {
System.out.println(s);
}
//function();
}
public static void function() throws NumberFormatException {
String s = "abc";
System.out.println(Double.parseDouble(s));
}

public static void main(String[] args) {
try {
function();
} catch (NumberFormatException e) {
System.err.println("非数据类型不能强制类型转换。");
// e.printStackTrace();
}
}

7.子类重写父类方法时的异常机制:

        1,子类重写父类方法要抛出与父类一致的异常,或者不抛出异常        2,子类重写父类方法所抛出的异常不能超过父类的范畴
        如下正常案例:
class A {
public void fun() throws RuntimeException {

}
}
class B extends A {
public void fun() throws IOException, RuntimeException {

}
}

8.自定义异常

public class MyException extends RuntimeException{}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: