(转载)throw和throws的区别

1.throw:(针对对象的做法)
抛出一个异常,可以是系统定义的,也可以是自己定义的。下面举两个例子:
抛出Java中的一个系统异常:
public class One {
public void yichang(){
NumberFormatException e = new NumberFormatException();
throw e;
}
public static void main(String[] args){
One test = new One();
try{
test.yichang();
}catch(NumberFormatException e){
System.out.println(e.getMessage());
}
}
}
抛出一个自定义的异常:

public class People {
public static int check(String strage) throws MyException{
int age = Integer.parseInt(strage);
if(age < 0){
throw new MyException("年龄不能为负数!");
}
return age;
}
public static void main(String[] args){
try{
int myage = check("-101");
System.out.println(myage);
}catch(NumberFormatException e){
System.out.println("数据格式错误");
System.out.println("原因:" + e.getMessage());
}catch(MyException e){
System.out.println("数据逻辑错误");
System.out.println("原因:" + e.getMessage());
}
}
}
public class MyException extends Exception{
private static final long serialVersionUID = 1L;
private String name;
public MyException(String name){
this.name = name;
}
public String getMessage(){
return this.name;
}
}
2.throws:(针对一个方法抛出的异常)
抛出一个异常,可以是系统定义的,也可以是自己定义的。
抛出java中的一个系统异常:
public class One {
public void yichang() throws NumberFormatException{
int a = Integer.parseInt("10L");
}
public static void main(String[] args){
One test = new One();
try{
test.yichang();
}catch(NumberFormatException e){
System.out.println(e.getMessage());
}
}
}
抛出一个自定义异常:
public class People {
public static int check(String strage) throws MyException{
int age = Integer.parseInt(strage);
if(age < 0){
throw new MyException("年龄不能为负数!");
}
return age;
}
public static void main(String[] args){
try{
int myage = check("-101");
System.out.println(myage);
}catch(NumberFormatException e){
System.out.println("数据格式错误");
System.out.println("原因:" + e.getMessage());
}catch(MyException e){
System.out.println("数据逻辑错误");
System.out.println("原因:" + e.getMessage());
}
}
}
public class MyException extends Exception{
private static final long serialVersionUID = 1L;
private String name;
public MyException(String name){
this.name = name;
}
public String getMessage(){
return this.name;
}
}
3.那么下面我要说究竟什么时候用哪种:
如果是系统异常的话可以什么都不用做,也可以针对方法抛出一个异常,因为系统异常是可以被系统自动捕获的,所以这个异常究竟是要在方法内部解决还是交给上层函数去解决其实效果是一样的。但是我查了很多资料,即使会抛出异常能被系统所捕获的话还是建议针对方法写一个throws,因为这样在完成一个大型任务的时候可以让别的程序员知道这里会出现什么异常。
如果是自己定义的异常,则必须要用throws抛出该方法可能抛出的异常,否则编译会报错。
4.注意:文章源自http://blog.chinaunix.net/uid-26359455-id-3130427.html
原文地址:https://www.cnblogs.com/gaoxufei/p/5886916.html