Java 面向对象:抛出异常throw、throws

package Exception.test;

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

/**
 * throws:异常的声明,说明某一个方法有可能会产生的异常。谁调用这个方法,谁就处理。如果不处理,继续向外抛出异常.
 * throw:手动的抛出异常:  new 异常类型()
 *
 */
public class TestException {
	public  void  m1() throws Exception {
		throw new Exception();//真正的抛出的异常
	}
	
	public static void main(String[] args) {
		TestException testException = new TestException();
		
			try {
				testException.m1();
			} catch (Exception e) {
				e.printStackTrace();
			}
		
			try {
				FileInputStream fileInputStream = new FileInputStream("abc");
				fileInputStream.read();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
package Exception.test;

public class Test1 {
	static void method() {
		try {
			throw new NullPointerException();
		} catch (ArithmeticException e) {
			System.out.println("ArithmeticException");
			throw e;
		}
	}
}
package Exception.test;

public class Test2 {

	public static void main(String[] args) {

		try {
			Test1.method();
		} catch (NullPointerException e) {
			System.out.println("NullPointerException");
		}
	}
}


你可能感兴趣的:(JavaDemo)