在java中,throw与throws有什么区别

如题所述

1、throw是在代码块内的,即在捕获方法内的异常并抛出时用的;

2、throws是针对方法的,即将方法的异常信息抛出去

3、可以理解为throw是主动(在方法内容里我们是主动捕获并throw的),而throws是被动(在方法上是没有捕获异常进行处理,直接throws的)

4、例子:

public void str2int(String str) throws Exception { //这里将得到的异常向外抛出
  try { 
    System.out.println(Integer.parseInt(str)); 

  } catch(NumberFormatException e) {
     //TODO 这里可以做一些处理,处理完成后将异常报出,让外层可以得到异常信息 
     throw new Exception("格式化异常"); 
  }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-06-03
java中throw是抛出的意思,Java中常用来表示抛出错误。而throw代表抛出一个错误,throws代表的是抛出多个错误。找错误的话可以在报错的板块或界面找到你自己写的那行代码。
第2个回答  2016-06-04
throws用于方法头部,声明该方法会抛出什么类型的异常;
throw用于方法体中,抛出某种类型的异常。
上代码:
public void fun() throws Exception {
try {

...

if (boolean) {
...

} else {
throw new MyException();

}
} catch (Exception e) {

...

throw e;

} finally {

... ...

]

}
第3个回答  2016-06-11
前者是声明, 厚者是表达式。

前者说你会扔某些异常。 后者是你真的扔某异常
第4个回答  2019-08-09

package practice;


public class pracrice_1 {

public static void main(String[] args) {

Vehicle vehicle = new Vehicle(4,5);

Vehicle car=new Car(4, 3, 4);

Vehicle truck = new Truck(4,3,4,5);

vehicle.showInfo();

car.showInfo();

truck.showInfo();

System.out.println(Integer.BYTES);

}

}

class Vehicle{

private int wheels;

private int weight;

public Vehicle(int wheels,int weight) {

this.weight=weight;

this.setWheels(wheels);

}

void showInfo(){

System.out.println("车轮个数为:"+this.getWheels()+"车重为:"+this.weight);

}

public int getWheels() {

return wheels;

}

public void setWheels(int wheels) {

this.wheels = wheels;

}

public int getWeight() {

return weight;

}

public void setWeight(int weight) {

this.weight = weight;

}

}

class Car extends Vehicle{

int loader;

public Car(int wheels,int weight,int loader) {

super(wheels,weight);

this.loader=loader;

}

void showInfo() {

System.out.println("车轮个数为:"+super.getWheels()+"车重为:"+this.getWeight()+"载人数为"+this.loader);

}

public int getloader() {

return loader;

}

public void setloader(int loader) {

this.loader = loader;

}

}

class Truck extends Car{

private int payload;

public Truck(int wheels, int weight, int loader,int payload) {

super(wheels, weight, loader);

this.payload=payload;

}

@Override

void showInfo() {

System.out.println("车轮个数为:"+super.getWheels()+"车重为:"+this.getWeight()+"载人数为"+this.loader+"载重量:"+this.payload);

}

}

建议你这样试试看:

      

这样做的好处:

注意事项:

相似回答