Java语言基础(9)日志打印和异常处理

1、log4j 1

Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码

CLASSPATH下建立log4j.properties。
右键 new file->log4j.properties
properties 属性文件
# 后面可以写注释

日志级别:ALL>TRACE>DEBUG>INFO>WARN>ERROR>FATAL>OFF

去maven中央仓库自行下载log4j-1.2.15.jar,添加到lib包下。maven仓库地址

log4j.rootLogger=DEBUG, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%p] %l %m%n

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yy-MM-dd-HH-mm-ss-SSS}|%p|%l|%m%n
log4j.appender.logfile.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.logfile.File=d:/logs/demo.log

在要输出日志的类中加入相关语句

import org.apache.log4j.Logger;

public class MyLogTest {
    static Logger logger = Logger.getLogger(MyLogTest.class.getName());

    public static void main(String[] args) {
        if (logger.isDebugEnabled()){
            logger.debug("debug判断:" + 1);
        }


        logger.trace("trace日志");
        logger.debug("debug日志");
        logger.info("info日志");
        logger.warn("warn日志");
        logger.error("error日志");
        logger.fatal("fatal日志");
    }

}

2、log4j 2

关于配置文件的名称以及在项目中的存放位置以及日志的leval

log4j 2.x版本不再支持像1.x中的.properties后缀的文件配置方式,2.x版本配置文件后缀名只能为".xml",“.json"或者”.jsn".

系统选择配置文件的优先级(从先到后)如下:
● (1).classpath下的名为log4j2-test.json 或者log4j2-test.jsn的文件.
● (2).classpath下的名为log4j2-test.xml的文件.
● (3).classpath下名为log4j2.json 或者log4j2.jsn的文件.
● (4).classpath下名为log4j2.xml的文件.

我们一般默认使用log4j2.xml进行命名。如果本地要测试,可以把log4j2-test.xml放到classpath,而正式环境使用log4j2.xml,则在打包部署的时候不要打包log4j2-test.xml即可。
trace<debug<info<warn<error<fatal

1.1、根节点Configuration

有两个属性:status和monitorinterval,有两个子节点:Appenders和Loggers(表明可以定义多个Appender和Logger).status用来指定log4j本身的打印日志的级别.monitorinterval用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s.

1.2、Appenders节点

常见的有四种子节点:Console、RollingFile、File、Socket.
1、Console节点用来定义输出到控制台的Appender.
● name:指定Appender的名字.
● target:SYSTEM_OUT 或 SYSTEM_ERR,一般只设置默认:SYSTEM_OUT.
● PatternLayout:输出格式,不设置默认为:%m%n.
2、File节点用来定义输出到指定位置的文件的Appender.
● name:指定Appender的名字.
● fileName:指定输出日志的目的文件带全路径的文件名.
● PatternLayout:日志的输出格式,不设置默认为:%m%n.

1.3、RollingFile节点用来定义超过指定大小自动归档(rolling)旧的创建新的的Appender.

● name:指定Appender的名字.
● fileName:指定输出日志的目的文件带全路径的文件名.
● PatternLayout:日志的输出格式,不设置默认为:%m%n.
● filePattern:指定归档日志文件的名称格式.
● Policies:指定滚动日志的策略,就是什么时候进行新建日志文件输出日志.
● Filter: 日志过滤,如:,表示debug级别以上的log会被打印。
3. loggers节点
logger表明,对某一文件,只有高于某级别,才被打印
AppenderRef:Logger的子节点,用来指定该日志输出到哪个Appender,如果没有指定,就会默认继承自Root.如果指定了,那么会在指定的这个Appender和Root的Appender中都会输出,此时我们可以设置Logger的additivity="false"只在自定义的Appender中进行输出。

1.4、比较完整的log4j2.xml配置模板

<?xml version="1.0" encoding="UTF-8"?>

<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->

<configuration status="info" monitorInterval="600" >

    <properties>
        <property name="LOG_HOME">D:/logs</property>
        <property name="FILE_NAME_INFO">std</property>
        <property name="FILE_NAME_ERROR">error</property>
    </properties>

    <!--先定义所有的appender -->
    <Appenders>
        <!--这个输出控制台的配置 -->
        <Console name="Console" target="SYSTEM_OUT">
            <!--             控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
            <!--             输出日志的格式 -->
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level (%class{36}.java %L) %M - %msg%n"/>
        </Console>

        <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用-->
        <File name="log" fileName="${LOG_HOME}/${FILE_NAME_INFO}.log" append="true">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>

        <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
        <RollingFile name="RollingFileInfo" fileName="${sys:user.home}/logs/info.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">

            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>

        <RollingFile name="RollingFileWarn" fileName="${sys:user.home}/logs/warn.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>

            <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${sys:user.home}/logs/error.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>

    </Appenders>

    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
    <loggers>
        <root level="info">
            <appender-ref ref="Console"/>
            <appender-ref ref="log" />
            <appender-ref ref="RollingFileInfo" />
            <appender-ref ref="RollingFileWarn"/>
            <appender-ref ref="RollingFileError"/>
        </root>
    </loggers>
</configuration>

1.5、Java代码


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class MyLogTest {

    static Logger logger = LogManager.getLogger(MyLogTest.class.getName());

    public static void main(String[] args) {
        if (logger.isDebugEnabled()) {
            logger.debug("debug模式日志");
        }

        logger.trace("trace日志");
        logger.debug("debug日志");
        logger.info("info日志");
        logger.warn("warn日志");
        logger.error("error日志");
        logger.fatal("fatal日志");
    }

}

3、异常处理

3.1、异常的基本概念

什么是异常,在程序运行过程中出现的错误,称为异常

public class ExceptionTest01 {

	public static void main(String[] args)	{
		int i1 = 100;
		int i2 = 0;
		
		int i3 = i1/i2;
		
		System.out.println(i3);	
	} 
}

没有正确输出,抛出了被0除异常
通过以上示例,我们看到java给我们提供了这样一个体系结构,当出现问题的时候,它会告诉我们,并且把错误的详细信息也告诉我们了,这就是异常的体系结构,这样我们的程序更健壮,我们可以把这个信息,再进行处理以下告诉用户。从上面大家还可以看到,java异常都是类,在异常对象中会携带一些信息给我们,我们可以通过这个异常对象把信息取出来

public class ExceptionTest01 {
    public static void main(String[] args) {
        StringBuffer sbf = new StringBuffer();
        for(long i=0;i<Long.MAX_VALUE;i++){
            sbf.append("T-"+i);
        }
    }
}

堆空间溢出
--------------------------------------------
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
public class ExceptionTest02 {
    public static void main(String[] args) {
        main(args);
    }
}

栈空间溢出
--------------------------------------------
Exception in thread "main" java.lang.StackOverflowError
	at com.test.ExceptionTest02.main(ExceptionTest02.java:5)
public class ExceptionTest05 {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String line = bf.readLine();
        System.out.println(line);
        bf.close();
    }
}

4、异常的分类

4.1、异常的层次结构

在这里插入图片描述

4.2、异常的分类

异常主要分为:错误、编译时异常、运行时异常

  1. 错误:如果应用程序出现了Error,那么将无法恢复,只能重新启动应用程序,最典型的Error的异常是:OutOfMemoryError、StackOverflowError
  2. 编译时异常:出现了这种异常必须显示的处理,不显示处理java程序将无法编译通过
  3. 运行时异常:此种异常可以不用显示的处理,例如被0除异常,java没有要求我们一定要处理

4.3、try、catch和finally

异常的捕获和处理需要采用try和catch来处理,具体格式如下:

try {
 
}catch(OneException e) {  

}catch(TwoException e) {

}finally {
   
}

● try中包含了可能产生异常的代码
● try后面是catch,catch可以有一个或多个,catch中是需要捕获的异常
● 当try中的代码出现异常时,出现异常下面的代码不会执行,马上会跳转到相应的catch语句块中,如果没有异常不会跳转到catch中
● finally表示,不管是出现异常,还是没有出现异常,finally里的代码都执行,finally和catch可以分开使用,但finally必须和try一块使用,如下格式使用finally也是正确的

try {

}finally {

}
public class ExceptionTest02 {

	public static void main(String[] args)	{
		int i1 = 100;
		int i2 = 0;
		//try里是出现异常的代码
		//不出现异常的代码最好不要放到try作用
		try {
			
			//当出现被0除异常,程序流程会执行到“catch(ArithmeticException ae)”语句
			//被0除表达式以下的语句永远不会执行
			int i3 = i1/i2; 
			
			//永远不会执行
			System.out.println(i3);	
			
		//采用catch可以拦截异常	
		//ae代表了一个ArithmeticException类型的局部变量
		//采用ae主要是来接收java异常体系给我们new的ArithmeticException对象
		//采用ae可以拿到更详细的异常信息
		}catch(ArithmeticException ae) {
			System.out.println("被0除了");
		}	
	} 
}

4.4、getMessage和printStackTrace()

如何取得异常对象的具体信息,常用的方法主要有两种:
● 取得异常描述信息:getMessage()
● 取得异常的堆栈信息(比较适合于程序调试阶段):printStackTrace();

public class ExceptionTest03 {

	public static void main(String[] args)	{
		int i1 = 100;
		int i2 = 0;
		try {
			int i3 = i1/i2; 
			System.out.println(i3);	
		}catch(ArithmeticException ae) {
			//ae是一个引用,它指向了堆中的ArithmeticException
			//通过getMessage可以得到异常的描述信息
			System.out.println(ae.getMessage());			
		}	
	} 
}
public class ExceptionTest04 {

	public static void main(String[] args)	{
		method1();
	} 
	
	private static void method1() {
		method2();
	}
	
	private static void method2() {
		int i1 = 100;
		int i2 = 0;
		try {
			int i3 = i1/i2; 
			System.out.println(i3);	
		}catch(ArithmeticException ae) {
			//ae是一个引用,它指向了堆中的ArithmeticException
			//通过printStackTrace可以打印栈结构
			ae.printStackTrace();	
		}	
	}
}

4.5、编译时异常

import java.io.FileInputStream;

public class ExceptionTest05 {

	public static void main(String[] args)	{
		FileInputStream fis = new FileInputStream("test.txt");
	} 
}

从上面输出可以看到,无法编译,它抛出了一个异常,这个异常叫做“编译时异常”FileNotFoundException,也就是说在调用的时候必须处理文件不能找到
处理FileNotFoundException

/*
import java.io.FileInputStream;
import java.io.FileNotFoundException;
*/

import java.io.*;

public class ExceptionTest06 {

	public static void main(String[] args)	{
		try {
			FileInputStream fis = new FileInputStream("test.txt");
			
		}catch(FileNotFoundException ffe) { //此异常为编译时异常,必须处理
			ffe.printStackTrace();
		}
	} 
}

4.6、finally关键字

finally在任何情况下都会执行,通常在finally里关闭资源

import java.io.*;

public class ExceptionTest07 {

	public static void main(String[] args)	{
		try {
			FileInputStream fis = new FileInputStream("test.txt");
			
			System.out.println("-------before fis.close--------");				
			//close是需要拦截IOException异常
			//在此位置关闭存在问题,当出现异常
			//那么会执行到catch语句,以下fis.close永远不会执行
			//这样个对象永远不会得到释放,所以必须提供一种机制
			//当出现任何问题,都会释放相应的资源(恢复到最初状态)
			//那么就要使用finally语句块
			fis.close();
			System.out.println("-------after fis.close--------");				
		}catch(FileNotFoundException e) { 
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
	} 
}

采用finally来释放资源

import java.io.*;

public class ExceptionTest08 {

	public static void main(String[] args)	{
		
		//因为fis的作用域问题,必须放到try语句块外,局部变量必须给初始值
		//因为是对象赋值为null
		FileInputStream fis = null;
		try {
			//FileInputStream fis = new FileInputStream("test.txt");
			fis = new FileInputStream("test.txt");
			
			/*
			System.out.println("-------before fis.close--------");				
			fis.close();
			System.out.println("-------after fis.close--------");				
			*/
		}catch(FileNotFoundException e) { 
			e.printStackTrace();
		}finally {
			try {
				System.out.println("-------before fis.close--------");	
				//放到finally中的语句,程序出现任何问题都会被执行
				//所以finally中一般放置一些需要及时释放的资源
				fis.close();
				System.out.println("-------after fis.close--------");				
			}catch(IOException e) {
				e.printStackTrace();
			}	
		}
	} 
}

深入finally

public class ExceptionTest09 {

	public static void main(String[] args)	{
		int i1 = 100;
		int i2 = 10;
		try {
			int i3 = i1/i2; 
			System.out.println(i3);	
			return;
		}catch(ArithmeticException ae) {
			ae.printStackTrace();	
		}finally {
			//会执行finally
			System.out.println("----------finally---------");
		}	
	} 
}
public class ExceptionTest10 {

	public static void main(String[] args)	{
		int i1 = 100;
		int i2 = 10;
		try {
			int i3 = i1/i2; 
			System.out.println(i3);	
			//return;
			System.exit(-1); //java虚拟机退出
		}catch(ArithmeticException ae) {
			ae.printStackTrace();	
		}finally {
			
			//只有java虚拟机退出不会执行finally
			//其他任何情况下都会执行finally
			System.out.println("----------finally---------");
		}	
	} 
}
public class ExceptionTest11 {

	public static void main(String[] args)	{
		int r = method1();
		//输出为:10
		System.out.println(r);
	} 
	
	/*
	   private static int method1()
	    {
	        byte byte0 = 10;
	        byte byte3 = byte0; //将原始值进行了保存
	        byte byte1 = 100;
	        return byte3;
	        Exception exception;
	        exception;
	        byte byte2 = 100;
	        throw exception;
	    }
	*/
	
	
	private static int method1() {
		int a = 10;
		try {
		 	return a;
		}finally {
			a = 100;			
		}	
	}
}
public class ExceptionTest12 {

	public static void main(String[] args)	{
		int r = method1();
		//输出为:100
		System.out.println(r);
	} 

	/*
	  private static int method1()
	    {
	        byte byte0 = 10;
	        byte0 = 50;
	        byte0 = 100;
	        break MISSING_BLOCK_LABEL_18;
	        Exception exception;
	        exception;
	        byte0 = 100;
	        throw exception;
	        return byte0;
	    }
	*/
	private static int method1() {
		int a = 10;
		try {
		 	a = 50;
		}finally {
			a = 100;			
		}	
		return a;
	}
}

4.7、final、finalize和finally?

finalize()是Object里面的一个方法,当一个堆空间中的对象没有被栈空间变量指向的时候,这个对象会等待被java回收

可以通过:System.gc();//手动调用垃圾回收 去测试这个finalize

4.8、如何声明异常

在方法定义处采用throws声明异常,如果声明的异常为编译时异常,那么调用方法必须处理此异常

import java.io.*;

public class ExceptionTest13 {

	public static void main(String[] args)	
	//throws FileNotFoundException, IOException { //可以在此声明异常,这样就交给java虚拟机处理了,不建议这样使用
	throws Exception { //可以采用此种方式声明异常,因为Exception是两个异常的父类
		/*
		//分别处理各个异常		
		try {
			readFile();
		}catch(FileNotFoundException e) { 
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
		*/	
		//可以采用如下方式处理异常
		//因为Exception是FileNotFoundException和IOException的父类
		//但是一般不建议采用如下方案处理异常,粒度太粗了,异常信息
		//不明确
		/*
		try {
			readFile();
		}catch(Exception e) {
			e.printStackTrace();	
		}
		*/
		readFile();
	} 
	
	private static void readFile() 
	throws FileNotFoundException,IOException { //声明异常,声明后调用者必须处理
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("test.txt");
		//}catch(FileNotFoundException e) { 
		//	e.printStackTrace();
		}finally {
			//try {
				fis.close();
			//}catch(IOException e) {
			//	e.printStackTrace();
			//}	
		}
	}
}
public class ExceptionTest14 {

	public static void main(String[] args)	{
		//不需要使用try...catch..,因为声明的是运行时异常
		//method1();
		
		//也可以拦截运行时异常
		try {
			method1();
		}catch(ArithmeticException e) {
			e.printStackTrace();		
		}
	} 
	
	//可以声明运行时异常
	private static void method1() throws ArithmeticException {
		int i1 = 100;
		int i2 = 0;
		// try {
			int i3 = i1/i2; 
			System.out.println(i3);	
	/*	
		}catch(ArithmeticException ae) {
			ae.printStackTrace();	
		}	
	*/	
	}
}

4.9、如何手动抛出异常

public class ExceptionTest15 {

	public static void main(String[] args)	{
		int ret = method1(1000, 10);
		if (ret == -1) {
			System.out.println("除数为0");
		}
		if (ret == -2) {
			System.out.println("被除数必须为1~100之间的数据");	
		}
		if (ret == 1) {
			System.out.println("正确");	
		}
		//此种方式的异常处理,完全依赖于程序的返回
		//另外异常处理和程序逻辑混在一起,不好管理
		//异常是非常,程序语句应该具有一套完成的异常处理体系
	} 
	
	private static int method1(int value1, int value2){
		if (value2 == 0) {
			return -1;	
		}
		if (!(value1 >0 && value1<=100)) {
			return -2;	
		}
		int value3 = value1/value2;
		System.out.println("value3=" + value3);	
		return 1;
	}
}

采用异常来处理参数非法

public class ExceptionTest16 {

	public static void main(String[] args)	{
		//int ret = method1(10, 2);
		//System.out.println(ret);
		/*
		try {
			int ret = method1(1000, 10);
			System.out.println(ret);
		}catch(IllegalArgumentException iae) {
		//ide为指向堆中的IllegalArgumentException对象的地址			
			System.out.println(iae.getMessage());
		}
		*/
		
		try {
			int ret = method1(1000, 10);
			System.out.println(ret);
		}catch(Exception iae) { //可以采用Exception拦截所有的异常
			System.out.println(iae.getMessage());
		}
		
	} 
	
	private static int method1(int value1, int value2){
		if (value2 == 0) {
			手动抛出异常
			throw new IllegalArgumentException("除数为0");
		}
		if (!(value1 >0 && value1<=100)) {
			//手动抛出异常
			throw new IllegalArgumentException("被除数必须为1~100之间的数据");
		}
		int value3 = value1/value2;
		return value3;
	}
}

throws和throw的区别?thorws是声明异常,throw是抛出异常
进一步了解throw

public class ExceptionTest17 {

	public static void main(String[] args)	{
		try {
			int ret = method1(1000, 10);
			System.out.println(ret);
		}catch(Exception iae) {
			System.out.println(iae.getMessage());
		}
		
	} 
	
	private static int method1(int value1, int value2){
		try {
			if (value2 == 0) {
				手动抛出异常
				throw new IllegalArgumentException("除数为0");
				
				//加入如下语句编译出错,throw相当于return语句
				//System.out.println("----------test111-----------");
			}
			if (!(value1 >0 && value1<=100)) {
				//手动抛出异常
				throw new IllegalArgumentException("被除数必须为1~100之间的数据");
			}
			int value3 = value1/value2;
			return value3;
		}finally {
			//throw虽然类似return语句,但finally会执行的
			System.out.println("-----------finally------------");	
		}	
	}
}

4.10、异常的捕获顺序

异常的捕获顺序应该是:从小到大

import java.io.*;

public class ExceptionTest18 {

	public static void main(String[] args)	{
		try {
			FileInputStream fis = new FileInputStream("test.txt");
			fis.close();
		}catch(IOException e) { 
			e.printStackTrace(); 
		}catch(FileNotFoundException e) { 
			e.printStackTrace();
		}	
		//将IOException放到前面,会出现编译问题
		//因为IOException是FileNotFoundException的父类,
		//所以截获了IOException异常后,IOException的子异常
		//都不会执行到,所以再次截获FileNotFoundException没有任何意义
		//异常的截获一般按照由小到大的顺序,也就是先截获子异常,再截获父异常
	} 
}

5、如何自定义异常

自定义异常通常继承于Exception或RuntimeException。如果需要调用方显示处理,则定义编译时异常,如果不需要对方显示处理,可以定义运行时异常。

import java.io.*;

public class ExceptionTest19 {

	public static void main(String[] args)	{
		try {
			method1(10, 0);
		}catch(MyException e) { 
			//必须拦截,拦截后必须给出处理,如果不给出处理,就属于吃掉了该异常
			//系统将不给出任何提示,使程序的调试非常困难
			System.out.println(e.getMessage());
		}
	} 
	
	private static void method1(int value1, int value2) 
	throws MyException { //如果是编译时异常必须声明
		if (value2 == 0) {
			throw new MyException("除数为0");	
		}
		int value3 = value1 / value2;
		System.out.println(value3);
	}
}

//自定义编译时异常
class MyException extends Exception {
	
	public MyException() {
		//调用父类的默认构造函数
		super();
	} 
	
	public MyException(String message) {
		//手动调用父类的构造方法
		super(message);	
	}
}
import java.io.*;

public class ExceptionTest20 {

	public static void main(String[] args)	{
		method1(10, 0);
	} 
	
	
	private static void method1(int value1, int value2) 
	//throws MyException { 
		if (value2 == 0) {
			//抛出编译时异常,方法可以不适用throws进行声明
			//但也也可以显示的声明
			throw new MyException("除数为0");	
		}
		int value3 = value1 / value2;
		System.out.println(value3);
	}
}

//自定义运行时异常
class MyException extends RuntimeException {
	
	public MyException() {
		//调用父类的默认构造函数
		super();
	} 
	
	public MyException(String message) {
		//手动调用父类的构造方法
		super(message);	
	}
}

6、方法覆盖与异常

方法覆盖的条件:
● 子类方法不能抛出比父类方法更多[大]的异常,但可以抛出父类方法异常的子异常

import java.io.*;

public class ExceptionTest21 {

	public static void main(String[] args)	{
	} 
}


interface UserManager {
	
	public void login(String username, String password) throws UserNotFoundException; 
	
}

class UserNotFoundException extends Exception {
	
}

class UserManagerImpl1 implements UserManager {
	
	//正确
	public void login(String username, String password) throws UserNotFoundException {
		
	}
}

//class UserManagerImpl2 implements UserManager {
	
	//不正确,因为UserManager接口没有要求抛出PasswordFailureException异常
	//子类异常不能超出父类的异常范围
	//public void login(String username, String password) throws UserNotFoundException, PasswordFailureException{
		
	//}
//}

class UserManagerImpl3 implements UserManager {
	
	//正确,因为MyException是UserNotFoundException子类
	//MyException异常没有超出接口的要求	
	public void login(String username, String password) throws UserNotFoundException, MyException {
		
	}
}


class PasswordFailureException extends Exception {
	
}

class MyException extends UserNotFoundException {
	
}

总结

  1. 异常的分类
  2. 编译时异常和运行时异常
  3. 异常的5个关键字try、catch、finally、throws、throw
  4. 异常的捕获顺序,先捕获小的,再捕获大的
  5. 自定义异常:
    ● 继承Exception,throw new的时候必须得throws抛出给调用者,相当于提示调用者必须捕获
    ● 继承RuntimeExcetion,throw new的时候不是必须throws抛出给调用者
    ● 建议:自定义异常尽量继承Exception,提示调用者必须处理异常,但是最终还是根据项目需求来
  6. 方法覆盖和异常的关系
  • 31
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值