Introduction

This topic introduces the basic concept of Exception Handling.

As you know, Nobody is perfect in this world. So, what if you are driving a car and suddenly something happens and the car stopped. How will you handle that situation?

Say the reason is “No Fuel”.



Similarly, while writing a program, if JVM finds something unacceptable then, it throws exceptions.

In this tutorial, you will learn about Exceptions and how to handle those exceptions.

Watch this Java video by Intellipaat:

Exception Handling Exception Handling

What is an Exception?

An Exception is an event that occurs during the execution of a program and it interrupts the normal flow of program executions.

Example:

Let’s say two persons orders Pine-Apple juice in a juice shop and the order came out to be Orange juice. This is a case of exception in java.

Learn more about Java Certification from this insightful Java Certification blog!

Some common problems which may cause exception:

Creating array object with negative size.

Accessing index of array which is not available

Dividing an integer value with zero.

Invoking instance members with null reference.

Recursive method invocation without conditional check.

public class ExceptionTest{

public static void main(String args[]){

System.out.println(“Main Started”);

String data= args[0]; //value at command line to variable

int x= Integer.parseInt(data); // to convert string value into int type

int res=10/x;

System.out.println(res);

}

}

The code will be compiled successfully.

While executing, JVM will use some threading concept to process the task like verify the class file, main method, etc.

After verifying the class and the required main method JVM will invoke the main method.

JVM will process the statements available in the main method one by one.

Case 1: java ExceptionTest (when value not provided from command line)

Main Started

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException:0

Case 2: java ExceptionTest Intellipaat (when string value is converted to int type)

Main Started

Exception in thread “main” java.lang.NumberFormatException:For input string:”Intellipaat”

Case 3: java ExceptionTest 0 (when 0 is provided from command line)

Main Started

Exception in thread “main” java.lang.ArithmeticException: / by zero

When a statement causes the problem then JVM will do the following tasks:

Analyze the problem.

Identify the class define in java language (may be exception or error)

Create the object of identified class with required message.

Throw the object(raise the event).

Once the object is thrown(event generated)

JVM will verify that any statement is available in the current block to catch the object or not.

If no statement found the control will be transferred to the caller method.

In the above program, the caller of main() method is JVM, so control will be transferred to JVM.

JVM will use default event handler to handle the event. The default handler will print the message to the console.

If JVM will handle the exception then program execution will be terminated abnormally.

Watch this Java video by Intellipaat:

Exception Handling Exception Handling

When to use Exception Handling?

If you want to catch the exception explicitly so that other statements from your application can be executed successfully, then you need to use exception handler in your program.

Problem Types



Problem occurred while executing the statement can be divided into two types:

Error

Exception

Error

It is a type of problem that will not be handled and the execution of the application will be terminated.

Depending on the reason, various classes are defined for various errors and all the error classes are subclasses of java.lang.Error class.

Handling Exception in program

You can use try and catch blocks to handle the exception.

Try and Catch Block

Try block should be followed by zero or more catch blocks.

When you expect the problems with any java statements, then place those statements inside the try block.

When exception is raised with the try block statements, then control will be transferred to the corresponding catch block.

Catch block should contain statements to handle the exceptions raised by the try block statements.

Syntax:

try{ // statements } catch(){ // statements }

You can write multiple catch block for one try block to handle each exceptions separately.

try{ // statements } catch(){ // statements }catch(){ // statements } …..

public class ExceptionTest{ public static void main(String args[]){ System.out.println(“Main Started”); int x=Integer.parseInt(args[o]); try{ int res=10/x; System.out.println(res); } catch(Exception e){ System.out.println(“Enter correct value”); } } }

In the above program:

Case 1:

java ExceptionTest 1 (enter value of x as 1 from command line)

10

Case 2:

java ExceptionTest 0 (enter value of x as 0 from command line)

Enter correct value

Want to know why the majority of Java Developers are moving towards Hadoop? Get to know in this 7 Reasons You Should Switch Career From Java to Hadoop blog!

Finally Block



There are some cases in which statements after catch block will not be executed:

When you have return statement inside the try and catch block.

When exception occurs in the try block and matching catch block is not found.

When exception occurs in the catch block, etc.

If you want to execute statements after catch block which fails to execute, then you have those statements in the finally block.

Syntax:

try{ // statements } catch(){ // statements }finally{ //statements }

Program to understand finally block

public class ExceptionTest{ public static void main(String args[]){ System.out.println(“Main Started”); int x=Integer.parseInt(args[o]); try{ int res=10/x; System.out.println(res); } catch(Exception e){ System.out.println(“Enter correct value”); } }finally{ System.out.println(“Main Completed”); }} }

In the above program, finally block will be executed always.

Types of Exception

There are two types of exceptions:

Checked exceptions

Unchecked exceptions

Checked Exception

These are also called compile time exceptions.

All the subclasses of java.lang.Exception except java.lang.RuntimeException and its sub classes are checked exception.

In other words, if you have any java statement that may cause any exception and that exception is verified by the compiler by forcing you to report the exceptions are called checked exceptions.

Checked Exception must be reported in any one of the two ways: Using try-catch block Propagating the exception using throws

If you are not reporting checked exception then you will get the following error message at compile time:

Unreported exception <ExceptionName>; must be caught or declared to be thrown.

public class Intellipaat{ public static void main(String args[]){ System.out.println(“Main Started”); Intellipaat i=new Intellipaat(); Object obj=i.clone(); System.out.println(“main completed”);} }}

Output:

Unreported exception

CloneNotSupportedException; must be caught or declared to be thrown

Watch this Spring video by Intellipaat: Exception Handling Exception Handling Unchecked Exception

These are also called as runtime exceptions.

lang.RuntimeException and its subclasses are unchecked exceptions.

If you have any java statement that may cause any exception and that exception is not verified by the compiler at compile time, then those exceptions are called as unchecked exceptions.

In case of unchecked exception, compiler is not responsible to verify whether you are reporting about the exception or not, i.e. unchecked exceptions may or may not be reported.

throw keyword

throw is a keyword used to throw exceptions explicitly.

You can throw any checked or unchecked exceptions.

You can throw any built-in or user-defined exceptions.

Syntax:

throw <throwableTypeObjectRef>

Example:

throw new NullPointerException();

throw new StudentNotFoundException();

class ThrowCheck{ static void show(){ try{ throw new NullPointerException("check"); }catch(NullPointerException ex) {System.out.println("show() has throw"); throw ex; // rethrowing the exception } }public static void main(String args[]){ try{ show(); }catch(NullPointerException ex) { System.out.println("Exception in main found"); } } }

Output:

show() has throw

Exception in main found

Come to Intellipaat’s Java Community if you have any queries on Java!

throws keyword

throws is a keyword used to propagate the exceptions to the caller method by specifying at method level.

You can define any checked or unchecked exceptions at method level.

You can define any built-in or user defined exceptions at method level.

When the exception is unchecked, then throws keyword is optional. But for checked exception throws keyword is mandatory.

class Throwscheck { static void show() throws IllegalAccessException { System.out.println("show() has exception "); throw new IllegalAccessException("demo"); } public static void main(String args[]){ try { show(); } catch(IllegalAccessException ex) { System.out.println("main() has show()"); } } }

Output:

show() has exception

main() has show()

User Defined Exception

The exceptions which are defined and implemented by application developer as per project requirements are called user defined exceptions.

Example:

StudentNotFoundException

InvalidDetailsException

UnsuccessfulAttemptsException

class UserCheck extends Exception{public UserCheck(String s) { super(s); } }public class Intellipaat{ public static void main(String args[]) { try{ throw new UserCheck("Intellipaat"); } catch (UserCheck ex) { System.out.println("caught exception"); System.out.println(ex.getMessage()); } } }

Output:

caught exception

Intellipaat

Interested in learning Java? Enroll in our Java Training now!

Conclusion

This brings us to the end of Exception Handling. In this tutorial, we learned in detail about the overview of Exception Handling.

We also covered almost all the main parts of Exception Handling. If you want to learn more, I would suggest to try our Intellipaat “Java” course that covers in-depth knowledge of most of the important topics like Basics of Java, Array,Exception Handling, Multi-threading, etc. to make you a good Java programmer.

Join Intellipaat Java training course and Certification today and let your career boom towards the domain of Software Developer.