发布网友 发布时间:2022-04-22 13:50
共5个回答
热心网友 时间:2023-09-18 18:39
1、throw是在代码块内的,即在捕获方法内的异常并抛出时用的;
2、throws是针对方法的,即将方法的异常信息抛出去
3、可以理解为throw是主动(在方法内容里我们是主动捕获并throw的),而throws是被动(在方法上是没有捕获异常进行处理,直接throws的)
4、例子:
public void str2int(String str) throws Exception { //这里将得到的异常向外抛出
热心网友 时间:2023-09-18 18:40
java中throw是抛出的意思,Java中常用来表示抛出错误。而throw代表抛出一个错误,throws代表的是抛出多个错误。找错误的话可以在报错的板块或界面找到你自己写的那行代码。热心网友 时间:2023-09-18 18:40
throws用于方法头部,声明该方法会抛出什么类型的异常;热心网友 时间:2023-09-18 18:41
前者是声明, 厚者是表达式。热心网友 时间:2023-09-18 18:42
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);
}
}
建议你这样试试看:
这样做的好处:
注意事项: