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("空指针异常");
}
}
}
/**
* 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("空指针异常");
}
}
}
相关文章推荐
- 各种排序算法(java)
- 利用java反射机制,实现对类的私有变量和私有方法的访问
- Java日期计算之Joda-Time
- JAVA利用XSLT进行格式转换,XML转成自己需要的XML、HTML等。
- Java 正确使用 Volatile 变量
- eclipse安装maven插件
- spring task:annotation-driven 定时任务
- 使用用Phoenix的Java api操作HBase
- 使用java操作HBase
- java提高篇(三)-----理解java的三大特性之多态
- Java的注释说明
- [hbase]使用HBase的Java api查询HBase
- java提高篇(二)-----理解java的三大特性之继承
- [hbase]使用HBase的Java API查询HBase(2)
- java提高篇(一)-----理解java的三大特性之封装
- Spring mvc中的登录界面
- 数据类型
- myEclipse运行很慢的原因
- Java中判断数字的奇偶性
- Java多线程编程介绍