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

try and catch keywords are used in combination to handle exceptions in java.

1) try and catch in java

Suspected code that may lead to an exception is enclosed within a try block, immediately followed by a catch block which determines what should be done if a particular exception is throws by the code enclosed within try block, as shown below.
try{
	System.out.println(string.length());
}
	catch(NullPointerException e){
		System.out.println("Please pass a valid string !");
}
If enclosed code may lead to different exceptions in different situations, one can use multiple suspected catch blocks after the try block.
try {
	System.out.println(string.length());
} catch (NullPointerException e) {
	System.out.println("Please pass a valid string !");
} catch (Exception e1) {
	System.out.println("Please pass a valid string !");
}
Few things must be noted here about try cathc combination:
1) Each try block must be followed by at least one cathc block or finally.
2) A try block may be followed by more than one catch block, but sub-classes of Exception class must come before any of their super classes.

2) Nested try and catch in java

A try catch block combination may be declared inside another try block as shown below.
package com.tb.demo;

class Main {
	void printSize(String string) {
		try {
			System.out.println(string.length());
			try {
				System.out.println(string.substring(4));

			} catch (NullPointerException e) {
				System.out.println("Please pass a valid string !");
			}
		} catch (NullPointerException e) {
			System.out.println("Please pass a valid string !");
		}

	}
}
A try catch block combination may be declared inside another catch block as shown below.
package com.tb.demo;

class Main {
	void printSize(String string) {
		try {
			System.out.println(string.length());
		} catch (NullPointerException e) {
			try {
				System.out.println(string.substring(4));

			} catch (NullPointerException e1) {
				System.out.println("Please pass a valid string !");
			}
		}

	}
}
In nested try catch, the inner try block uses its own catch block as well as catch block of the outer try, if required.

Throwable, class overrides toString() from java.lang.Object, that means toString() can be used to print name of the exception thrown, as shown below:
package com.tb.demo;

class Main {
	void printSize(String string) {
		try {
			System.out.println(string.length());
		} catch (NullPointerException e) {
			System.out.println(e.toString());
		}
	}

	public static void main(String args[]) {
		Main main = new Main();
		main.printSize(null);
	}
}
Output : java.lang.NullPointerException

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