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

java中的throw与throws的区别

2015-12-18 16:39 543 查看
package Throws;

/**

* throw:是抛出某个异常对象,作为一条代码语句执行

* throws:是写在方法体的定义上的,后面跟要抛出的多个异常类

*对于throws来说,异常可以不用解决,谁来调用这个方法,就同样接收了这些异常

*最终会抛向主程序入口,如果一直没有解决,而异常有很严重,则程序不能执行

*/

public class Throws {

public static void main(String[] args) throws InterruptedException {

Throws p=new Throws();

p.print();

p.speak();

}

public void print() throws InterruptedException{

print1();

}

public void print1() throws InterruptedException{

print2();

}

public void print2() throws InterruptedException{

System.out.println("你听得到吗");

Thread.sleep(2000);

System.out.println("我听到了");

}

public void speak(){

try {

String str=null;

System.out.println(str.length());

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException("空指针异常");

}


}

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