The exception handling in java is one of the powerful tool to handle the runtime errors so that normal flow of the application can be reconstructed.
Contents
- 1 What is exception
- 2 Advantage of Exception Handling
- 3 Types of Exception
- 4 Ranking of Java Exception classes
- 4.0.0.0.1 Java try block
- 4.0.0.0.2 Syntax of java try-catch
- 4.0.0.0.3 Java catch block
- 4.0.0.0.4 Problem without exception handling
- 4.0.0.0.5 Solution by exception handling
- 4.0.0.0.6 Java Multi catch block
- 4.0.0.0.7 Java nested try example
- 4.0.0.0.8 Java finally block
- 4.0.0.0.9 Usage of Java finally
- 4.0.0.0.10 Java throw keyword
- 4.0.0.0.11 Java throw keyword example
- 4.0.0.0.12 else
- 4.0.0.0.13 Output:
- 4.0.0.0.14 Java throws keyword
- 4.0.0.0.15 Java throws example
- 4.0.0.0.16 Java Random Exception
- 4.0.0.0.17 else
What is exception
In java, exception is an incident that reduces the normal flow of the program. It is an object which is thrown at runtime.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. Exception genrely reduces the normal flow of the application that is why we use exception handling.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions:
- Checked Exception
- Unchecked Exception
- Error
Difference between checked and unchecked exceptions
- Checked Exception: The classes that extend knowable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
- Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions g. ArithmeticException, Null Pointer Exception, Array Index out of Bounds Exception etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
- Error: Error is irrecoverable g. out of Memory Error, Virtual Machine Error, Assertion Erroretc.
Ranking of Java Exception classes
Checked and UnChecked Exceptions
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used enclosed by the way(method) .
Java try block must be followed by either catch or finally block.
Syntax of java try-catch
- try{
- //code that may throw exception
- }catch(Exception_class_Name ref){} Syntax of try-finally block
- try{
- //code that may throw exception
- }finally{}
Java catch block
Java catch block is used to handle the Exception. It must be used after the try block.
You can use multiple catch block with a single try.
Problem without exception handling
Let’s try to understand the problem if we don’t use try-catch block.
public class Testtrycatch1{
public static void main(String args[]){ int data=50/0;//may throw exception System.out.println(“welcome to progremercoding.com”);
} }
Output:
Exception in alternate main java.lang.ArithmeticException:/ by zero
As out put in the above example, rest of the code is not applied (in such case, rest of the code… statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be applied.
Solution by exception handling
Let’s see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);} System.out.println(“welcome to progremercoding.com.”);
} }
Output:
Exceptioninthreadmainjava.lang.ArithmeticException:/byzero
welcome to progremercoding.com. |
Now, as out put in the above example, rest of the code is applied i.e. welcome to progremercoding.com statement is printed.
Java Multi catch block
If you have to apply different tasks at the
incident of different Exceptions, use java multi catch block.
Let’s see a simple example of java multi-catch block.
- public class TestMultipleCatchBlock{
- public static void main(String args[]){
- try{
- int a[]=new int[5]; a[5]=30/0;
- }
- catch(ArithmeticException e){System.out.println(“task1 is completed”);}
- catch(ArrayIndexOutOfBoundsException e){System.out.println(“task2 completed”); }
- catch(Exception e){System.out.println(“frequenttask completed”);
- }
- System.out.println(“welcome to progremercoding.com.”);
- } }
Output:task1 completed
welcome to progremercoding.com |
Java nested try example
Let’s see a simple example of java nested try block.
class Excep6{
public static void main(String args[]){
try{ try{
System.out.println(“going to divide”);
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5]; a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);} System.out.println(“other statement);
}catch(Exception e){System.out.println(“handeled”);} System.out.println(“normal flow of code..”);
} 1. }
Java finally block
Java finally block is a block that is used to apply important code such as closing connection, flow etc.
Java finally block is a way(method) s applied whether exception is handled or not. Java finally block follows try or catch block.
Usage of Java finally
Case 1
Let’s see the java finally example where exception doesn’t happen. class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5; System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);} finally{System.out.println(“finally block is alway(method) s applied”);} System.out.println(“rest of the code…”);
}
Output:5
finally block is always executed rest of the code… |
}
Java throw keyword
The Java throw keyword is used to definitively throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw random exception. We will see random exceptions later.
The syntax of java throw keyword is given below.
- throw exception;
Java throw keyword example
In this example, we have produced the validate way(method) that takes integer value as a parameter. If the age is less than 18, we are throwing the Arithmetic Exception other wise print a message welcome to vote.
- public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException(“not valid”);
else
System.out.println(“welcome to vote”);
}
public static void main(String args[]){ validate(13);
System.out.println(“rest of the code…”);
} }
Output:
Exception in alternate main java.lang.ArithmeticException:not valid
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may happen an exception so it is best for the programmer to provide the exception handling code so that normal flow can be reconstructed.
Exception Handling is mainly used to handle the checked exceptions. If there happens any unchecked exception such as Null Pointer Exception, it is programmers fault that he is not applying check up before the code being used.
Syntax of java throws
- return_type way(method) _name() throws exception_class_name{
- //way(method) code
- }
4.
Java throws example
Let’s see the example of java throws clause which describes that checked exceptions can be propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException(“device error”);//checked exception
}
void n()throws IOException{ m();
}
void p(){
try{ n();
}catch(Exception e){System.out.println(“exception handled”);}
}
public static void main(String args[]){ Testthrows1 obj=new Testthrows1(); obj.p();
System.out.println(“normal flow…”); } }
Output:
exception handled
normal flow…
Java Random Exception
If you are creating your own Exception that is known as random exception or user-circle exception. Java random exceptions are used to random ize the exception according to user need.
By the help of random exception, you can have your own exception and message. Let’s see a simple example of java random exception.
class InvalidAgeException expand Exception{ InvalidAgeException(String s){
super(s);
} }
class TestRandomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException(“not valid”);
else
System.out.println(“welcome to vote”);
}
public static void main(String args[]){
try{ validate(13);
}catch(Exception m){System.out.println(“Exception happened: “+m);}
System.out.println(“rest of the code…”);
} }
Output:
Exception happened:
InvalidAgeException:
not valid rest of the code…