赞
踩
目录
- try{
- //存放所有可能出现异常的代码
- } [ catch( 捕获相应的异常)…[0…N]]{
- // 出现相应异常后处理方式
- }[finally]{
- // 不是强制要求写
- // 无论是否发生异常,都会执行finally代码块,一般进行资源的释放
- //关闭资源操作
- }
- int[] arr = {10,20,30};
- try {
- arr = null;
- System.out.println(arr[3]);
- } catch (ArrayIndexOutOfBoundsException e) {
- System.out.println("数组下标异常!");
- } catch (NullPointerException e) {
- System.out.println("空指针异常");
- }
- System.out.println("arr[1]");
- //File是Java中文件操作类
- File file = new File("src/java19_1_21/test.txt");
- //输入不是键盘输入,是将文件输入到Scanner类中
- Scanner scanner = null;
- try {
- scanner = new Scanner(file);
- System.out.println("文件正确加载完毕");
- } catch (FileNotFoundException e) {
- System.out.println("文件不存在!");
- e.printStackTrace();
- } finally {
- //最后处理的一些代码
- System.out.println("文件正常处理完毕”);
- }
- public static void main(String[] args) {
- try{
- test();
- }catch(NullPointerException e) {
- System.out.println("捕获空指针异常!");
- e.printStackTrace();
- }
- }
- // 调用test方法有可能会产生空指针异常,但是test方法不处理此异常,谁调用谁处理
- public static void test() throws NullPointerException,ArrayIndexOutOfBoundsException{
- String str = null;
- System.out.println(str.length());
- }
- public static void main(String[] args) {
- fun();
- System.out.println("fun之后的代码");
- }
- public static void fun(){
- throw new NullPointerException("抛个异常玩玩");
- //抛出异常后,方法就会结束
- }
Error:
Exception:(java我们关注这个错误)
- import java.util.Scanner;
-
-
- //自定义类模拟登录
- public class LoginTest {
- public static final String ID = "huweilong";
- public static final String PASSWORD = "123456";
-
-
- public static void main(String[] args) {
- try {
- login();
- System.out.println("登录成功!");
- } catch (UserNameException e) {
- e.printStackTrace();
- } catch (PasswordException e) {
- e.printStackTrace();
- }
- }
-
-
- public static void login() {
- Scanner scanner = new Scanner(System.in);
- System.out.print("请输入用户名:");
- String id = scanner.next();
- System.out.print("请输入密码:");
- String password = scanner.next();
- if (!id.equals(ID)) {
- throw new UserNameException("用户名错误!");
- }
- if (!password.equals(PASSWORD)) {
- throw new PasswordException("密码错误!");
- }
- }
- }
-
-
- //用户名验证
- class UserNameException extends RuntimeException {
- public UserNameException(String msg) {
- super(msg);
- }
- }
-
-
- //密码验证
- class PasswordException extends RuntimeException {
- public PasswordException(String msg) {
- super(msg);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。