Introduction
There are three categories of errors: Syntax error, Runtime error, and Logic error. A Syntax error arises because a rule of the language has not been followed; they are detected by the compiler. Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out. A logic error occurs when the program does not perform the way it was intended to.
An exception is one of the abnormal conditions that can occur during the execution of a program. Exceptions in Java are handled using an API which is given in java.lang package in the form of various Exception classes.

An exception can occur for several reasons; some of the general reasons are the following:
- A user has entered invalid data.
- A file needs to be opened but cannot be found.
- A network connection failed in the middle of the communication.
Catching an Exception
To catch an exception in Java you need to use a try block with one or more catch blocks. In each catch clause, you can define one specific type of exception that it is prepared to handle. You can put all the code in a try block that can potentially cause an exception to be generated.
Syntax
try
{
// code that may cause of Exception
}
catch(......)
{
//Code of handling the exception
}
Note-you can have more than one catch block for a single try.
Syntax
try{
// code that may cause of Exception
}catch(......)//1
{
//Code of handle the exception
}
catch(...2...)//2
{
//Code of handle the exception
}
Example
- class MultipleCatch
- {
- public static void main(String arg[])
- {
- int a,x;
- try{
- a = Integer.parseInt(arg[0]); // NumberFormat + ArrayIndex
- x = 100 / a; // ArithmeticException
- System.out.println("x = "+x);
- }catch(ArithmeticException ex) // only for ArithmeticException
- {
- System.out.println("Ohh! sorry , this is / by 0 ");
- }
- catch(NumberFormatException ex) // only for NumberFormatException
- {
- System.out.println("invalid number for type casting , these alphabet");
- }
- catch(ArrayIndexOutOfBoundsException ex) // only for ArrayIndexOutOfBoundsException
- {
- System.out.println("sorry there is no command line arguments");
- }
- System.out.println("Thanxxxxxxxxxxxxxxxxxxx");
- }
- }
Throwing exception
To throw an exception you simply use the throw with an object reference. All the methods use the throw statement to throw an exception.
Syntax
public int div(int a, int b) throws AirthmeticException
{
// body of methods
}
throw someThrowableObject ;
Example



Join the conversation! Your thoughts help the community grow.