package object.chapter7;
import java.util.Scanner;
/*
使用throws抛出异常
*/
public class ThrowsTest {
/*
通过try-catch捕获并处理异常
*/
//main方法抛出异常,后续代码不执行
public static void main(String[] args) throws Exception{
ThrowsTest throwsTest=new ThrowsTest();
throwsTest.throwTest();
System.out.println("继续执行程序");
}
//方法往外抛出异常,可以抛多个异常
public void throwTest() throws Exception {
int i = 100;
if (i == 100) {
throw new Exception("throw一个异常...");
}
}
// public void throwTest() {
// int i = 100;
// if (i == 100) {
// throw new RuntimeException("throw一个异常..."); // RuntimeException非检查异常
// }
// }
// if(i==100){
// try {
// throw new Exception("throw一个异常...");
// }catch (Exception e){
// e.printStackTrace();
// }
// }
//}
/*
通过throws继续声明异常
*/
// public static void main(String[] args) throws Exception {
//
// divide();
//
// }
/*
输入被除数和除数,计算商并输出
@throws Exception
*/
public static void divide() throws Exception{
Scanner in=new Scanner(System.in);
System.out.println("请输入被除数:");
int num1=in.nextInt();
System.out.println("请输入除数:");
int num2=in.nextInt();
System.out.println(String.format("%d/%d=%d",num1,num2,num1/num2));
}
}
Java学习-第21天-throw、throws异常
最新推荐文章于 2025-03-25 10:54:27 发布