package com.itheima.d8_exception_handle_runtime;
import java.util.Scanner;
/**
* 需求:需要输入一个合法的价格为止 要求价格大于0
*/
public class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true){
try {
System.out.println("请您输入合法的价格:");
String priceStr = sc.nextLine();
//转换成double类型的价格
double price = Double.valueOf(priceStr);
//判断价格是否大于0
if(price > 0){
System.out.println("定价:" + price);
break;
}else{
System.out.println("价格必须是正数~~");
}
} catch (Exception e) {
System.out.println("用户输入的数据有毛病,请您输入合法的数值,建议为正数~~");
}
}
}
}
package com.itheima.d9_exception_custom;
public class ItheimaAgellleagealRRuntimeException extends RuntimeException{
public ItheimaAgellleagealRRuntimeException() {
}
public ItheimaAgellleagealRRuntimeException(String message) {
super(message);
}
}
package com.itheima.d9_exception_custom;
public class ItheimaAgellleagealException extends Exception{
public ItheimaAgellleagealException() {
}
public ItheimaAgellleagealException(String message) {
super(message);
}
}
package com.itheima.d9_exception_custom;
public class ExceptionDemo {
public static void main(String[] args) {
// try {
// checkAge(34);
// } catch (ItheimaAgellleagealException e) {
// e.printStackTrace();
// }
try {
checkAge2(-23);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void checkAge2(int age) {
if (age < 0 || age > 200) {
//抛出去一个异常对象给调用者
//throw:在方法内部直接创建一个异常对象,并从此点抛出
//throws: 用在方法申明上的,抛出方法内部的异常
throw new ItheimaAgellleagealRRuntimeException(age + "is illeagal!");
} else {
System.out.println("年龄合法:推荐商品给其购买!");
}
// public static void checkAge(int age) throws ItheimaAgellleagealException {
// if (age < 0 || age > 200) {
// //抛出去一个异常对象给调用者
// //throw:在方法内部直接创建一个异常对象,并从此点抛出
// //throws: 用在方法申明上的,抛出方法内部的异常
// throw new ItheimaAgellleagealException(age + "is illeagal!");
// } else {
// System.out.println("年龄合法:推荐商品给其购买!");
// }
// }
}
}