流程控制:
throws, 声明异常. 将当前方法中的异常交给调用者处理
throw, 抛出异常. 主动创造异常
示例:
/**信息处理类
* 学员登录
* @return
* @throws Exception
*/
public Student login() throws Exception {
/* 获取登录需要的数据 */
//学号
int id = SystemUtil.inputInteger("学号");
//密码
String password = SystemUtil.inputString("密码");
/* 查询 */
//根据id查询
Student stu = studentData.selectById(id);
//判断登录结果
if(stu == null || !stu.getPassword().equals(password))
throw new Exception("学号或密码错误! 登录失败!");
return stu;
}
package com.test;
import java.util.InputMismatchException;
import com.controller.SystemController;
/**
* 测试类, 程序入口
把异常抛给main方法集中处理
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
//创建对象
SystemController controller = new SystemController();
/* 程序主流程 */
while (true) {
try {
/* 菜单 */
controller.menu.show();
/* 选择 */
int choice = controller.menu.choose();
/* 执行 */
controller.execute(choice);
} catch (InputMismatchException e) {
System.out.println("您输入的数据不合法, 请重试!");
} catch (Exception e) {
// e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
}