Java throw, finally and throws keywords

throw

Till now we caught exceptions which were generated automatically, but in some cases, we need to raise an exception from our program manually. To raise an exception throw keyword is used. Below is the syntax of throw statement.

throw object;

Here, the object is an object of an exception class. We have to create an object of required exception type and then use that object with throw keyword. In the below sample, we are throwing ArithmeticException manually and when we use throw statement, Java handles it same way as an automatic exception and the corresponding catch block will be called and executed.

/*
This is a simple Java program about Exception Handling.
Call this file KH_throw.java.
*/

class KH_throw {
	public static void main(String args[]) {
		try {
			System.out.println("Before throw.");
			throw new ArithmeticException();
		}
		catch (ArithmeticException exc) {
			System.out.println("Exception caught.");
		}
		System.out.println("After try catch block.");
	}
}

Download the code  Run the code

Output:

Before throw.
Exception caught.
After try catch block.

finally

When we write programs there will many of cases where we need to open a file, open a database connection or open a socket etc. at the beginning of a method. When the method exits, we need to make sure we close all opened connections.

We include all statements such as opening a file inside try block. Now we need to close the file after successful try block execution as well as if any exception is caught. The same code needs to be executed in both cases. To achieve this, we can use finally block. The finally block always gets called at the end of the try block and catch block. Below is syntax to use finally:

try {
    // block of code to monitor for errors
}
catch (ExcepType1 exOb) {
    // handler for ExcepType1
}
catch (ExcepType2 exOb) {
    // handler for ExcepType2
}
//...
finally {
    // finally code
}

The below program demonstrates how finally is used here. As you can see in the output, finally gets executed in both cases.

/*
This is a simple Java program about Exception Handling.
Call this file KH_finally.java.
*/
// Use finally.
class UseFinally {
	public static void genException(int i) {
		int t;
		int nums[] = new int[2];
		System.out.println("Receiving " + i);
		try {
			switch(i) {
				case 0:
					t = 10 / i;
					break;
				case 1:
					nums[4] = 4;
					break;
				case 2:
					return;
			}
		}
		catch (ArithmeticException exc) {
			System.out.println("Can not divide by Zero");
			return;
		}
		catch (ArrayIndexOutOfBoundsException exc) {
			System.out.println("No matching element found.");
		}
		finally {
			System.out.println("Leaving try.");
		}
	}
}

class KH_finally {
	public static void main(String args[]) {
		for(int i=0; i < 3; i++) {
			UseFinally.genException(i);
			System.out.println();
		}
	}
}

Download the code  Run the code

Output:

Receiving 0
Can not divide by Zero
Leaving try.

Receiving 1
No matching element found.
Leaving try.

Receiving 2
Leaving try.

throws

A method which does not handle exceptions within its body, has to specify what type of exceptions it might throw by using throws keyword. Its syntax is:

returntype methodName(parameterlist) throws exceptionlist {
    // body
}

But in our previous cases, we did not use this keyword because all our exceptions are handled and the method is error proof. When a method is defined with throws an exception, Java itself will remember this point.

Below program demonstrates the same, here we are using the prompt method to read input from the user and we have used throws keyword with IOException and inside main we have handled this exception.

/*
This is a simple Java program about Exception Handling.
Call this file KH_throws.java.
*/
class KH_throws {
	
	public static char prompt(String str) throws java.io.IOException {
		System.out.print(str + ": ");
		return (char) System.in.read();
	}

	public static void main(String args[]) {
		char ch;
		try {
			ch = prompt("Enter a letter");
		}
		catch(java.io.IOException exc) {
			System.out.println("I/O exception occurred.");
			ch = 'X';
		}
		System.out.println("You pressed " + ch);
	}
}

Download the code  Run the code

Output:

Enter a letter: a
You pressed a
<<< Methods in Throwable, Java’s Built-in Exceptions, and Custom ExceptionJava I/O – built in I/O classes >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .