How to use Exception handling in java?

Exception are run time anomalies or unusual conditions that a program may encounter while executing. Anomalies might include conditions such as division by zero, access to an array outside of is bounds, or running out of memory or disk space.

Exceptions are of two kinds, namely, synchronous exception and asynchronous exceptions. Errors such as “out of range index” and “over flow” belong to the synchronous type exceptions. The errors that are caused by events beyond the control of the program are called asynchronous exceptions.

The purpose of the Exception handling is to provide means to detect and report an “exceptional circumstance” so that the appropriate action can be taken.

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

Try

Catch

Finally

Throw

Throws

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let’s take a scenario:

Suppose there is 3 statements in your program and there occurs an exception at statement 1st, rest of the code will not be executed i.e. statement 2nd and 3rd will not run. If we perform exception handling, rest of the exception will be executed. That is why we use exception handling in java.

Example:-

In this program we use try and catch.

//code

class demo

{

public static void main(String arg[])

{

try

{

System.out.println(5/0);

}

catch(Exception e)

{

System.out.println(“U can’t devide by zero”);

}

System.out.println(“Hello india”);

}

}

Step 1: Name it as “excep.java”and save the file in any location i saved at “c:/kiran/program”.

Step 2: Set the paath,without path setting our java file is not compile.

Step 3: Now write the following code for checking my java file is compiling or not.

javac excep.java

My java program compiled successfully.

Step 4: Write the following code in command prompt. press enter and see the output.