throws是将方法中的异常抛出给调用处处理,而throw是抛出的使我们创建的一个异常(我们自己实例化的一个异常对象)
package com.CoderLB;
public class Test {
public static void main(String[] args) {
System.out.println("程序开始执行");
try{
String [] strs = {"1234","12ss3"};
System.out.println(Integer.parseInt(strs[1]));
}catch (NumberFormatException e){
e.printStackTrace();
}
System.out.println("执行完毕");
}
}
输出:
第10行中的e.printStackTrace();e是一个对象。这个对象是虚拟机创建的。如果程序出现了异常则虚拟机会创建一个对应类型的异常对象,当然也可以创建一个异常对象。
package com.CoderLB;
public class Test {
public static void main(String[] args) {
System.out.println("程序开始执行");
try{
String [] strs = {"1234","12ss3"};
System.out.println(Integer.parseInt(strs[1]));
}catch (NumberFormatException e){
e=new NumberFormatException("数字格式错误");
e.printStackTrace();
}
System.out.println("执行完毕");
}
}
输出:
使用throw抛出异常
package com.CoderLB;
public class Test {
public static void main(String[] args) {
System.out.println("程序开始执行");
try{
String [] strs = {"1234","12ss3"};
System.out.println(Integer.parseInt(strs[1]));
}catch (NumberFormatException e){
throw new NumberFormatException("数字格式错误");
}
System.out.println("执行完毕");
}
}
输出:
程序并未执行完毕,而是遇到异常终止了
package com.CoderLB;
public class Test {
public static void main(String[] args) {
System.out.println("程序开始执行");
try{
String [] strs = {"1234","12ss3"};
System.out.println(Integer.parseInt(strs[1]));
}catch (NumberFormatException e){
try{
throw new NumberFormatException("数字格式错误");
}catch (NumberFormatException e1){
e1.printStackTrace();
}
}
System.out.println("执行完毕");
}
}
输出:
如果出现异常,则JVM会实例化一个异常对象,然后被try catch中捕获到,之后再catch中处理,在catch中我们自己创建了一个新的异常对象抛出,我们新创建的这个异常需要我们自己重新使用try catch处理,否则交给虚拟机处理。