3) Creating a method that throws an exception

Example 1:

import java.io.FileNotFoundException;

public class DempThrowsException {
	public void readFile(String file) throws FileNotFoundException {
		boolean found = findfile(file);
		if(!found) {
			throw new FileNotFoundException("Missing file");
		}
	}

	private boolean findfile(String file) {
		// return true if file is located
		return false;
	}
}

Example 2 :

import java.io.FileNotFoundException;

public class DempThrowsException {
	public void readFile(String file) throws FileNotFoundException {
		boolean found = findfile(file);
		if(!found) {
			checkAndThrowException();
		}
	}

	private void checkAndThrowException() throws FileNotFoundException {
		throw new FileNotFoundException("Missing file");	
	}

	private boolean findfile(String file) {
		// return true if file is located
		return false;
	}
}

1) Handle the exception :

2) Declare it to be thrown:

3) Handle and declare:

Example 3:

import java.io.FileNotFoundException;

public class DempThrowsException {
	public void readFile(String file) throws FileNotFoundException {
		if (file == null) {
			throw new NullPointerException();
		}
		boolean found = findfile(file);
		if (!found) {
			throw new FileNotFoundException("Missing file");
		}
	}

	private boolean findfile(String file) {
		// return true if file is located
		return false;
	}
}

Example 4:

import java.io.FileNotFoundException;

public class ThrowExceptions {
	void method1() throws Throwable {

	}

	void method2() throws Error {

	}

	void method3() throws Exception {

	}

	void method4() throws RuntimeException {

	}

	void method5() throws FileNotFoundException {

	}
}

Example 5:

import java.io.FileNotFoundException;

public class ThrowExceptions {
	void method1() throws Throwable {

	}

	void method2() throws Error {

	}

	void method3() throws Exception {

	}

	void method4() throws RuntimeException {

	}

	void method5() throws FileNotFoundException {

	}

	void method6() {
		try {

		} catch (Throwable e) {

		}

	}

	void method7() {
		try {

		} catch (Error e) {

		}
	}

	void method8() {
		try {

		} catch (Exception e) {

		}
	}

	void method9() {
		try {

		} catch (RuntimeException e) {

		}
	}

	void method10() {
		try {

		} catch (FileNotFoundException e) {

		}
	}
}

Last updated