Exception

学习JAVA第五天

今天学习了Exception(异常)

异常的处理方式一共有两种

  1. jvm处理运行 java程序的抽象计算机 异常名称 异常信息 异常出现的位置
  2. 自己处理
    (1)try catch finally
    (2)throws

所有的异常的父类都是Exception;
平时可能遇到的异常
1.ArithmeticException
2.ArrayIndexOutOfBoundsException
3.NullPointerException

异常的类型
1.运行时异常 extends RuntimeException
2.编译异常 必须自己处理

我们也自己尝试了一下自己处理异常的方式
代码如下:

package com.nbufe.test;

public class Test2
{
    public static void main(String[] args) {
        Person person=new Person();
        try {
            person.setAge(-1);
        }catch (AgeException e)
        {
            e.printStackTrace();
        }
        int age=person.getAge();
        System.out.println(age);
    }

}
package com.nbufe.test;

public class Person {
    public int getAge() {
        return age;
    }

    public void setAge(int age) throws AgeException {
        if(age<0||age>=150)
        {
            throw new AgeException("你可能不是人");
        }
        else
        this.age = age;
    }

    private int age;

}

package com.nbufe.test;

public class AgeException extends Exception{

    public AgeException(String message) {
        super(message);
    }
}

作业:自己编写一个jdbc时登陆异常的代码

package com.nbufe.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class TestLogin {
    public static void main(String[] args) throws Exception {

            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.创建连接
            Connection connection= DriverManager.getConnection
                    ("jdbc:mysql://127.0.0.1:3306/nbufe?useSSL=true&characterEncoding=utf-8&user=chestnut&password=321");
            System.out.println("创建连接成功");
            String sql="select * from user where username =1 and password =781376680" ;
             PreparedStatement preparedStatement=connection.prepareStatement(sql);
        //5.执行sql语句得到结果集
             ResultSet resultSet=preparedStatement.executeQuery();
        //6.处理结果集
        if (resultSet.next())
        {
            System.out.println("11111");
        }
        else
        {
            throw new LoginException("登陆错误");
        }
         }
}

package com.nbufe.test;

public class LoginException extends Exception {
    public LoginException(String message) {
        super(message);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值