目录
异常的概念以及异常分类
概念:
异常:指的是在程序执行过程中,出现的非正常情况,最终会导致JVM的非正常停止。
分类:
java.lang.Throwable:类是 java语言中所有错误或异常的父类
Exception:编译器异常,进行编译(写代码)java程序出现的问题
RuntimeException:运行期异常,java程序运行过程中出现的问题
异常相当于程序得了一个小毛病(感冒,发烧),把异常处理掉,程序可以继续执行(吃点药,卖力工作
Error:错误
错误相当于程序得了一个无法治愈的毛病(非典,艾滋),必须修改代码,程序才能执行
异常:
SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd");
Date date= null;
try {
date = sdf.parse("19999-09");
} catch (ParseException e) {
e.printStackTrace();
}
错误:
int[] arr=new int[1024*1024*1024];
异常产生过程的解析
throw关键字
throw关键字
作用:
可以使用throw关键字在指定方法中抛出异常
使用格式:
throw new xxxException("异常产生的原因");
注意:
1.throw关键字必须写在方法的内部
2.throw关键字后边new的对象必须是Exception或者Exception的子类对象
3.throw关键字抛出的指定的异常,我们必须处理这个异常对象
throw关键字后边创建的RuntimeException或者是RuntimeException的子类对象,我们可以不处理,默认交给JVM处理(打印异常对象,中断)
throw关键字后边创建的是编译异常(写代码的时候报错),我们就必须处理这个异常,要么throws,要么try...catch
public static void main(String[] args) {
int[] arr={1,2};
System.out.println(getElement(arr,2));
}
public static int getElement(int[]arr,int index)
{
/*
可以对传递过来的参数数组,进行合法性校验,
如果数据arr的值是null,那我们就抛出空指针异常
*/
if(arr==null)
{
throw new NullPointerException("传递数组的值为空");
}
/*
对传递过来的参数index进行合法性校验
如果index范围不再数组索引范围内
我们就抛出索引越界异常,告知方法的调用者"创建的索引超出了数组的使用范围"
*/
if(index<0||index>=arr.length)
{
throw new ArrayIndexOutOfBoundsException("索引越界");
}
int ele=arr[index];
return ele;
}
Objects非空判断
Objects类中的静态方法
public static<T> requireNonNull(T obj):查看指定引用对象不是null
源码:
public static<T> T requireNonNuLL(T obj){
if(obj==null)
throw new NullPointerException();
return obj;
public static void main(String[] args) {
method(null);
}
public static void method(Object obj){
Objects.requireNonNull(obj,"传递为空");
}
Throws关键字
throws关键字:异常处理的第一种方式,交给别人处理
作用:
当方法内部抛出异常时候,我们就必须处理这个异常对象
可以使用throws关键字处理对象,会把异常对象声明抛出给方法的调用者(自己不处理,给别人处理),最终转交给JVM处理
使用格式:在方法声明时使用
修饰符 返回值类型 方法名(参数列表)throws AAAException,BBBException...{
throw new AAAException("产生原因”);
throw new BBBException("产生原因“);
}
注意:
1.throws关键字必须写在方法声明处
2.throws关键字后边声明的异常必须是Exception或者是Exception的子类
3.方法内部如果抛出了多个异常对象,那么throws后边必须声明多个异常
如果抛出的异常对象有子夫类关系,那么直接声明父类异常即可
4.调用了一个声明就抛出异常的方法,我们就必须处理声明的异常
要么继续使用throws声明抛出,交给方法的调用者处理,最终交给JVM
要么try...catch自己处理异常
public static void main(String[] args) throws Exception {
readfile("c:\\a.tx");
}
/*定义一个方法,对传递的文件路径进行合法性判断
* ,如果文件路径不是“c:\\a.txt"那么抛出异常
* 注意:
* FileNotFoundException是编译异常,抛出了编译异常,必须处理这个异常
* 可以使用Throws继续声明抛出FileNotFoundException这个异常对象
* */
public static void readfile(String fileName) throws FileNotFoundException, IOException {
if (!fileName.equals("c:\\a.txt")) {
throw new FileNotFoundException();
}
}
try...catch异常处理
try...catch异常处理的第二种方式,自己处理异常
格式:
try{
可能产生的异常代码
}catch(定义一个异常的变量,用来接收try中抛出的异常对象){
异常处理逻辑,抛出异常对象后,怎么处理异常对象
一般在工作中,会把异常的信息记录到一个日志中
}
...
catch(异常变量 变量名){
}
注意:
1.try中可能会抛出多个异常对象,那么就可以使用多个catch来处理这些异常对象
2.如果try中产生了异常,那么就会执行catch中的异常处理逻辑,执行完毕catch中的处理逻辑,继续执行try...catch之后的代码
如果try中没有产生异常,那么就不会执行catch中异常的处理逻辑,执行玩try中的代码,继续执行try...catch之后的代码
public static void main(String[] args) {
try{
readfile("d:\\a.tx");
}catch(IOException e){
System.out.println(e);
}
System.out.println("后续代码");
}
public static void readfile(String fileName) throws IOException {
if(!fileName.endsWith(".txt")) {
throw new IOException("文件异常1111");
}
System.out.println("没有问题");
}
finally代码块
格式:
try{
可能产生的异常代码
}catch(定义一个异常的变量,用来接收try中抛出的异常对象){
异常处理逻辑,抛出异常对象后,怎么处理异常对象
一般在工作中,会把异常的信息记录到一个日志中
}
...
catch(异常变量 变量名){
}finally{
无论是否出现异常都会执行
}
注意:
1.finally不能单独使用,必须和try一起使用
2.finally一般用于资源释放(资源回收),无论程序是否出现异常,最后都要资源释放
public static void main(String[] args) {
try {
//可能会产生异常的代码
readfile("c:\\a.tx");
} catch (IOException e) {
//异常处理逻辑
e.printStackTrace();
} finally {
System.out.println("资源释放");
}
}
public static void readfile(String fileName) throws IOException {
if (!fileName.endsWith(".txt")) {
throw new IOException("文件异常1111");
}
System.out.println("没有问题");
}
异常注意事项
多异常的捕获
try{
int[] arr={1,2,3};
System.out.println(arr[3]);
}catch(Exception e){
System.out.println(e);
}
try {
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(1);
list.add(1);
System.out.println(list.get(3));
}catch(Exception e)
{
System.out.println(e);
}
try{
int[] arr={1,2,3};
System.out.println(arr[3]);
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(1);
list.add(1);
System.out.println(list.get(3));
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}catch (IndexOutOfBoundsException e)
{
System.out.println(e);
}
try {
int[] arr={1,2,3};
System.out.println(arr[3]);
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(1);
list.add(1);
System.out.println(list.get(3));
}catch (IndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("后续代码");
子父类的异常
-如果父类抛出了多个异常,子类重写父类方法时,抛出和父类相同的异常或者是父类异常的子类或者不抛出异常
-父类方法没有抛出异常,子类重写父类方法也不抛出异常,此时子类产生该异常,只能捕获处理,不能声明
注意:
父类异常是什么样子,子类异常就是什么
public class Fu {
public void show01()throws NullPointerException{}
public void show02()throws IndexOutOfBoundsException{}
public void show03()throws IndexOutOfBoundsException{}
public void show04(){}
}
class Zi extends Fu{
public void show01() throws NullPointerException{}
public void show02() throws ArrayIndexOutOfBoundsException{}
public void show03() {}
public void show04(){
try{
throw new Exception("xin");
}catch (Exception e)
{
System.out.println(e);
}
}
自定义异常类
自定义异常类:
java提供的异常类,不够我们使用,需要自己定义一些异常类
格式:
public class XXXException extends Exception | RunException{
添加一个空参数的构造方法
添加一个带异常信息的构造方法
}
注意:
1.自定义异常类一般读属以Expection 结尾,索命该类是一个异常类
2.自定义异常类,必须继承Exception或者RuntimeException
继承Exception:那么自定义异常类就是一个编译器异常,如果方法内部抛出了异常,那就必须处理这个异常
继承RuntimeException:那么自定义异常类就是一个运行期异常,无需处理,交给虚拟机处理(中断处理)
public RegisterException() {
}
public RegisterException(String message)
{
super(message);
}
自定义异常类的练习
要求:模拟注册操作,如果用户名已经存在,则抛出异常并提示:亲,该用户名已经被注册
分析:
1.使用数组保存已经注册过的用户名(数据库)
2.使用Scanner获取用户输入的注册用户名(前端,页面)
3.定义一个方法,对用户输入的用户名进行判断
遍历存储已经注册过用户名的数组,获取每一个用户
使得获取到的用户名和用户输入的用户名比较
true:
用户名已经存在,抛出ReisterException异常,告知用户“亲,该用户名已经被注册”
false:
继续遍历比较
如果循环结束了,还没有找到重复的用户名,提示用户:"恭喜你,注册成功!"
static String[] usernames = {"张三", "李四", "王五"};
public static void main(String[] args) /*throws RegisterException*/ {
Scanner sc = new Scanner(System.in);
System.out.println("请输入要注册的用户名:");
String username = sc.next();
checkusername(username);
}
public static void checkusername(String username) /*throws RegisterException*/ {
for (String s : usernames) {
if (s.equals(username)) {
throw new RegisterException("亲,用户名已被注册");
}
}
System.out.println("恭喜你注册成功");
}