Exception Handling in Java

In this article we will see 'Exception Handling in Java', Throwable class, and Java Exception heirarchy.

Exception handling is the practice to handle unwanted runtime situations, runtime situation includes null values, file not found etc.

Exception handling provides an alternate about what should happen if things doesn't went the way they are expected to happen.
void printSize(String string) {
In the code above if string is passed null, a NullPointerException exception will arise and program will fail, to overcome this situation the programmer has to make sure even if null value is passed to printSize() method the program should not fail.

One way of doing this is exception handling as shown below:
catch(NullPointerException e){
	System.out.println("Please pass a valid string !");
More information about try and catch in coming articles.

Exception Hierarchy in Java

When an unwanted situation occurs in runtime, an exception is said to be thrown, this thrown exception is always an object of one of the defined exception classes in Java.

All exceptions are subclasses of class Throwable, which is at the top of exception class hierarchy.

Exception handling deals with all the exceptions thrown which are subclasses of Exception class and does not deal with errors.

Types of Exception in Java

There are three type of exceptions in java, 1) Checked Exception, 2) Unchecked Exceptions and 3) Errors

1) Checked Exception

Checked exceptions are the exceptions which can be predicted by the compiler and are forced to be handled by the programmer, for example FileNotFoundException.

2) Unchecked Exceptions

Unchecked exceptions are the exceptions which can not be predicted by the compiler and programmer has to predict about them to write handling code to avoid any unforeseen condition in runtime, these exceptions are subclasses of RuntimeException class, for example NullPointerException.

3) Errors

Errors can not be handled programatically, for example StackOverFlowError.

In this article we have seen 'Exception Handling in Java', Throwable class, and Java Exception hierarchy. In upcoming articles we will see more about Java.

About The Author

Nagesh Chauhan

Nagesh Chauhan has 8+ years of software design and development experience in variety of technologies like - Core Java, Java 8 (Streams, Lambda), J2EE (Servlet, JSP), Spring Framework (MVC, IOC, JDBC, SECURITY etc), Spring Boot and Microservices, Kafla, Redis, Cassandra and Spark.