In this article we will see 'What is finally keyword in Java', and how to use finally with combination of try and catch with example.

1) 'finally' keyword in Java

A 'finally' block can be used followed by a try or try-catch blocks, code written in finally block will be executed for sure no matter of an exception is occurred or not, to use a finally block a try block must be there.
		try {
			System.out.println(string.length());
		} catch (NullPointerException e) {
			System.out.println(e.toString());
		}finally {
			System.out.println("This will run for sure.");
		}
If a try has one or more catch blocks, finally is placed after the last catch and if try does not have any catch block finally will be placed after try. A try block much have either a catch or a finally block or both.
		try {
			System.out.println(string.length());
		} finally {
			System.out.println("This will run for sure.");
		}

2) 'throws' keyword in Java

If a code is capable of throwing an exception, it should be enclosed inside a try block or the method having the code must throw the expected exception using 'throws', as shown below:
	void printSize(String string) throws NullPointerException,Exception {
			System.out.println(string.length());
	}
This tells the compiler, if an exception occurs in the code enclosed inside the body of the method, those exceptions should be thrown to the calling method.

Now the calling method will handle those exceptions using try, or try-catch or try-finally or will throw them again to his calling method.
	void printSize(String string) throws NullPointerException,Exception {
			System.out.println(string.length());
	}
	
	// Calling method 
	void print(){
		try {
			printSize("STRING");
		} catch (NullPointerException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
If throwing goes on and no method actually handles the exception the exception is ultimately handled by java runtime and this would terminate the program.

3) 'throw' keyword in Java

'throw' keyword is used to throw an exception explicitly, these may be user defined exceptions or runtime exceptions, as shown below:
	void printSize(String string) {
		if (string == null)
			throw new NullPointerException();
	}
This is useful when a programmer wants to throw appropriate exceptions based on unexpected behaviours the code may amount to.

In this article we have seen 'What is 'finally' keyword in Java', and how to use finally with combination of try and catch with example. In upcoming articles we will see more about Java.
  • By Techburps.com
  • Nov 7, 2017
  • Core Java