Exceptions and exception handling

First, the concept of exceptions

  1. definition:

    Refers to the abnormal run-error occurs, that is wrong in the future when the program starts execution period arise.

  2. Processing attitude:

       When Exception caught will be easy to make a deal, even if it is an exception to this error message printed out, this is a good programming practice.
       If you do not deal with, that is to quietly hide the error, but the error still exists, but can not see it. This is a very dangerous programming practice, absolutely can not do that, there must be an exception to capture make a deal, it can not handle to put an exception is thrown, so that other methods to deal with. Anyway, it can not be captured after an abnormal but do not make the appropriate treatment, which is a very bad programming practice.

Second, the malfunction classification

  1. Exception Handling way:

        Use the method declaration throws out an exception thrown: a method
            throws Exception
                Exception class is the foundation class for all exception classes can handle, throws Exception class will throw all exception classes can be processed in the.
        Method two: Manually throw out
            throw + exception object
                exception object thrown out, and then the kind of statement on the method of writing to throw exceptions.
        Method three:
            the try ... cacth a finally ...

        try {
			//处理业务代码
		} catch (Exception e) {
			//抛出异常处理,具体异常具体定
			e.printStackTrace();
		} finally{
			//最终都需执行的代码
			//一般做资源清理工作
		}

       We generally use printStackTrace () method to print this information abnormal, use this method to print out all the wrong information, including information on the use of getMessage () method to print out. To a new error object to call it out before using this method. Because it is specific to an error object inside the method.

  1. Five key Java exception handling: try, catch, finally, throw, throws

Here Insert Picture Description

  1. Malfunction classification
    Here Insert Picture Description
    sample code:
package com.lixu.javabase.exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 异常Demo
 */
public class ExceptionDemo {
	
	/**
	 * 任何方法往外抛能处理的异常的时候都有一种简单的写法:“throws Exception”
	 * 因为Exception类是所有能处理的异常类的根基类,因此抛出Exception类就会抛出所有能够被处理的异常类里了。
	 * 使用“throws Exception”抛出所有能被处理的异常之后,这些被抛出来的异常就是交给JAVA运行时系统处理了,
	 * 而处理的方法是把这些异常的相关错误堆栈信息全部打印出来。
	 */
	void mothod() throws Exception{
		
	}
	
	
	public void method1() throws Exception{
		//不处理,可能产生FileNotFoundException异常
		@SuppressWarnings("resource")
		FileInputStream flStream = new FileInputStream("mytext.txt");
		//这里有可能会产生IOException异常
	    int b = flStream.read();
	    while (b != -1) {
	          System.out.println((char)b);
	          b = flStream.read();
        }
	}

	public void method2() throws FileNotFoundException,IOException {
		@SuppressWarnings("resource")
		FileInputStream flStream = new FileInputStream("mytext.txt");
		int b = flStream.read();
		while (b != -1) {
	          System.out.println((char)b);
	          b = flStream.read();
      }
	}
	
	public void method3(){
		FileInputStream flStream = null;
		try {
			flStream = new FileInputStream("mytext.txt");
			int b = flStream.read();
			while(b != -1){
				System.out.println((char)b);
		        b = flStream.read();
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e){
			System.out.println(e.getMessage());
		} finally{
			try {
              /**
              * 前面已经把一个文件打开了,不管打开这个文件时有没有错误发生,即有没有产生异常,最后都一定要把这个文件关闭掉,
              * 因此使用了finally语句,在finally语句里面不管前面这个文件打开时是否产生异常,在finally这里执行in.close()都能把这个文件关闭掉,
              * 关闭文件也有可能会产生异常,因此在finally里面也使用了try……catch语句去捕获有可能产生的异常。
              */
			  flStream.close();
			} catch(Exception e){
			  e.printStackTrace();
			}				          
		}		
	}
	
}

Third, custom exception

package com.lixu.javabase.exception;


/**
 * 自定义异常MyException
 */
public class MyException extends Exception {

	private int id;
	
	/**
	 * 自定义异常类的构造方法
	 * @param message
     * @param id
     */
	public MyException(String message,int id) {
		super(message);
		this.id = id;
	}
	
	/**
	 * 获取异常的代码
	 * @return
	 */
	public int getId() {
		return id;
	}
		
}

Test-defined exceptions

package com.lixu.javabase.exception;

import java.text.MessageFormat;

public class TestMyException {

	public static void main(String[] args){
		TestMyException tmException = new TestMyException();
		tmException.manage();
	}
	
	//throws MyException,抛出我们自定义的MyException类的异常。
	public void regiter(int num) throws MyException{
		if(num < 0){
			//使用throw手动抛出一个MyException类的异常对象。
			throw new MyException("人数为负值,不合理", 1);
		}
		System.out.println(MessageFormat.format("登记人数:{0}",num));
	}
	
	public void manage() {
         try {
             regiter(-100);
         } catch (MyException e) {
             System.out.println("登记失败,错误码:"+e.getId());
             e.printStackTrace();
         }
         System.out.println("操作结束");
    }
}

Here Insert Picture Description

Fourth, exception handling summary
Here Insert Picture Description
reference: https: //www.cnblogs.com/xdp-gacl/p/3627390.html

Published 16 original articles · won praise 3 · Views 536

Guess you like

Origin blog.csdn.net/outdata/article/details/102457154