java中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;
}
}
温馨提示:答案为网友推荐,仅供参考
相似回答