Java异常处理——捕获异常
认识异常
1.异常是导致程序中断运行的一种指令流,如果不对异常进行正确处理,则可能导致程序的中断执行,造成不必要的损失。
2.异常范例
package hwd;
class Exc{//创建类
int i = 10;//定义属性
}
public class ExceptionDemo01 {//创建类
public static void main(String[] args) {//主方法
int a = 10;//定义属性
int b = 0;//定义属性
int temp = a / b;//计算
System.out.println(temp);//打印结果
}
}

处理异常
1.异常格式:
tyr{
//异常语句
}catch(Exception){
}finally{
//一定会执行的代码
}
package hwd;
class Exc{//创建类
int i = 10;//定义属性
}
public class ExceptionDemo01 {//创建类
public static void main(String[] args) {//主方法
int a = 10;//定义属性
int b = 0;//定义属性
int temp = 0;//定义属性
try{
temp = a / b;//计算
}catch(Exception e){
System.out.println(e);//打印结果
}
}
}

package hwd;
class Exc{//创建类
int a = 10;//定义属性
int b = 10;//定义属性
}
public class ExceptionDemo01 {//创建类
public static void main(String[] args) {//主方法
int temp = 0;//定义属性
Exc e = null;
// e = new Exc();
try {
temp = e.a/e.b;//计算
System.out.println(temp);//打印结果
}catch(NullPointerException e1){//捕获异常
System.out.println("空指针异常" + e1);//打印异常
}catch(ArithmeticException e2){//捕获异常
System.out.println("算数异常" + e2);//打印异常
}finally{
System.out.println("程序推出");//打印结果
}
}
}

常见的异常
1. 数组越界异常:ArrayIndexOutOfBoundsException
2. 数字格式化异常:NumberFormatException
3. 算数异常:ArithmeticException
4.空指针异常:NullPointerException
throws关键字
1. 在定义一个方法的时候可以使用throws关键字声明,在使用throws声明的方法表示此方法不处理异常,抛给方法的调用者处理
2. 格式
public void tell () throws Exception{}
package hwd;
public class ExceptionDome02 {//定义类
public static void main(String[] args) throws Exception{//主方法
tell(10,0);//调用方法
}
public static void tell(int i, int j) throws ArithmeticException{//创建方法
int temp = 0;//定义属性
temp = i/j;//计算
System.out.println(temp);//打印结果
}
}

throw关键字
1. throw关键字抛出一个异常,抛出的时候直接抛出异常类的实例化对象即可
package hwd;
public class ExceptionDome02 {//创建类
public static void main(String[] args) {//主方法
try{
throw new Exception("实例化异常对象");//实例化异常对象
}catch( Exception e){//捕获异常
System.out.println(e);//打印异常
}
}
}

自定义异常
1. 自定义异常直接继承Exception就可以完成自定义异常类
package hwd;
/**
*
*
* 创建自定义异常
*
*/
class MyException extends Exception{
public MyException(String msg){
super(msg);
}
}
public class ExceptionDome02 {
public static void main(String[] args){
try{
throw new MyException("自定义异常");//抛出异常
}catch(MyException e){//捕获异常
System.out.println(e);//打印异常
}
}
}

Java异常处理详解与实战
本文介绍了Java异常处理的基本概念和重要性,包括认识异常、处理异常的try-catch-finally结构、常见异常类型如ArrayIndexOutOfBoundsException、NumberFormatException和ArithmeticException。此外,还讲解了如何使用throws声明和throw关键字来处理异常,以及自定义异常的实现方式。通过实例展示了如何在代码中捕获和处理这些异常,确保程序的稳定运行。
346

被折叠的 条评论
为什么被折叠?



