Throw, Throws,Finally


Before catching an exception it is must to be thrown first. This means that there should be a code somewhere in the program that could catch the exception. We use throw statement to throw an exception or simply use the throw keyword with an object reference to throw an exception. A single argument is required by the throw statement i.e. a throwable object. The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. Example as :

public class ThrowExample {
	public static void main(String[] args) {
		// suppose we don't want account balance should be less than 1000
		int minimumBalance = 1200;

		try {
			// first withdraw
			minimumBalance -= 200;

			// second withdar
			minimumBalance -= 100;

			if (minimumBalance < 1000) {// if minimum balance reached, exception
										// should be thrown
				throw new Exception("minimum balance reached");
			/* throw Exception, with message (minimum balance reached) */

		} catch (Exception e) { // thrown exception is being handled there
			System.out.println(e); // will print type and label of exception as
									// passes


If a method might throw an exception and the program doesn’t know how to handle this exception. Then the user should declare a throws clause after the function name, and the java runtime automatically handle this. Example is :

public class ThrowsExample {
	public static void main(String[] args) throws Exception {
		/* throws clause with Exception or type of exception */
		int arr[] = { 1, 2, 3 };
		System.out.println(arr[5]); // no need to handle through try/catch block



When an exception occurs the code after that line is not executed under certain circumstances. now suppose that we have created a database connection or opened a file then, due to program termination the connection or file remains open and if we open these in other files then it may pose some problems. So to prevent this we use finally. A finally block will be executed whether an exception occurred or not. If the program terminated before reaching the finally block. via System.exit(), finally will not be called

public class ExceptionBasics {
	public static void main(String args[]) {
		int nums[] = new int[4];
		try {
			System.out.println("Before exception is generated.");
			// Generate an index out-of-bounds exception.
			nums[10] = 10; // array only generated for 4 elements and we are
							// accessing 10th element
			System.out.println("this won't be displayed");
		} catch (ArrayIndexOutOfBoundsException exc) {
			System.out.println("Index out-of-bounds!");
			System.out.println("This will be displayed always");

You may also like...