目录
Java异常处理-捕获异常:
Java异常处理-常见异常
throws: 跟在方法声明后面,后面跟的是异常类名
throw: 用在方法体内,后面跟的是异常类对象名
自定义异常
Java异常处理-捕获异常:
认识异常
处理异常
常见异常
throws关键字
throw关键字
自定义异常
算数异常,除数不能为零.例如
class Exce{
int i=10;
}
public class ExceptionDemOo1 {
public static void main(String[] args) {
int a=10;
int b=0;
int tem=a/b;
System.out.println("tem");
}
}
空指针异常
class Exce{
int i=10;
}
public class ExceptionDemOo1 {
public static void main(String[] args) {
Exce e=null;
System.out.println(e.i);
}
}
Java异常处理-常见异常
ArithmeticException是出现异常的运算条件时,抛出此异常。例如,一个整数“除以零”时,抛出此类的一个实例。
class Exce{
int i=10;
}
public class ExceptionDemOo1 {
public static void main(String[] args) {
int a=10;
int b=10;
int temp=0;
try {
temp=a/b;
}catch(ArithmeticException e) {//运算条件错误时,抛出此异常
System.out.println(e);
}
System.out.println(temp);
}
}
举例
class Exce{
int a=10;
int b=10;
}
public class ExceptionDemOo1 {
public static void main(String[] args) {
int temp=0;
Exce e=null;
e=new Exce();
System.out.println(temp);
System.out.println("程序推出");
}
}
捕获异常,处理异常
class Exce{
int a=10;
int b=0;
}
public class ExceptionDemOo1 {
public static void main(String[] args) {
int temp=0;
Exce e=null;
e=new Exce();
try {
temp=e.a/e.b;
System.out.println(temp);
}catch(NullPointerException e2) {
System.out.println("空指针异常:"+e2);
}catch(ArithmeticException e2) {
System.out.println("算数异常:"+e2);
}
System.out.println("程序推出");
}
}
1、在定义一个方法的时候可以使用throws关键字声明,使用throws声明的方法表示此方法不处理异常,抛给方法的调用者处理
2、格式:
public void tell() throws Exception0
throws: 跟在方法声明后面,后面跟的是异常类名
throw: 用在方法体内,后面跟的是异常类对象名
throw的特点:
throw:这是一个用在方法体里面的异常,用于直接后面跟上异常的对象名
只能抛出一个异常对象名
表示抛出异常,由方法体内的语句来处理
public class ExceptionDemOo1 {
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);
}
}
例如
public class ExceptionDemOo1 {
public static void main(String [] args){
try {
throw new Exception("实例化异常对象");
}catch(Exception e) {
System.out.println(e);
}
}
}
自定义异常
自定义异常类应该包含2个构造器:一个是默认的构造器,另一个是带有详细信息的构造器。
1、自定义异常的步骤
(1)继承 Exception 或 RuntimeException
(2)定义构造方法
(3)使用异常
自定义异常直接继承Exception就可以完成自定义异常类
class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
public class ExceptionDemOo1 {
public static void main(String [] args) {
try {
throw new MyException("自定义异常");
}catch(MyException e) {
System.out.println(e);
}
}
}