Showing posts with label Exception Handling tutorial. Show all posts
Showing posts with label Exception Handling tutorial. Show all posts

Thursday, December 13, 2018

Difference Between checked Exception and Unchecked Exception in Java

In this post you will learn what is checked and unchecked Exceptions and difference between them. The following are the differences between them.

Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword. 

Example: FileNotFoundException, EndOfFileException etc.

So the compiler at compile time will check if a certain method is throwing any of the checked exceptions or not,if yes it will check whether the method is handling that exception either with “Try&Catch” or “throws”,if in case the method is not providing the handling code then compiler will throw error saying “Unreported Exception”

For example

import java.io.*
class Example
{
public static void main(String[] args)
 {
PrintWriter pw=new PrintWriter("xyz.txt"); //creating a new printwriter object to write in a file named "xyz.txt"
pw.println("Hello World");
 } }

The above snippet is supposed to print “Hello World” in file named “xyz.txt”

There may be a chance of file “xyz.txt” is not present in specified directory,so the compiler will check if any handling code is provided in case file is not present

In above snippet handling code is not provided either with “Try&Catch” or “throws” so the compiler will throw error

The same example with some modification:

import java.io.*
Class Example
{
public static void main(String[] args) throws FileNotFoundException
 {
PrintWriter pw=new PrintWriter("xyz.txt"); //creating a new printwriter object to write in a file named "xyz.txt"
pw.println("Hello World");
}}
In this example handling code is provided with “throws” so compiler will not throw any error.



Unchecked Exceptions:

There are some exceptions which do not occur regularly in a program,and compiler will not check for those exceptions,these kind of exceptions are called Unchecked Exceptions

Example: ArithmeticException, NullPointerException etc

For example:

class Example{
public static void main(String[] args){
System.out.println(10/0); //Arithmetic Exception
}
The above program should throw “Arithmetic Exception” as division with “0” is not allowed

In this case the program compiles fine because compiler will not check for “Unchecked Exceptions” but the program will throw error at “Run Time” as division with “0” is illegal.

Sunday, February 26, 2017

How to use finally block in Java

In this post we will discuss and learn what is finally keyword in java and how it is useful in java,why sun people introduced this concept in java. This is one of the core concept in exception handling. Although try and catch provides terrific mechanism for trapping and handling exceptions.It is not recommended to place the clean up code inside try block because there is no guarantee for execution of all statements inside  the try block.  For example,you allocated a network socket or opened a file somewhere in the guarded region,each exception handler would have to close the file or release the socket. It makes the programmer too easy to forget to clean up the code,and also lead to a lot of redundant code. To overcome this problem java offers finally block.

finally  create a block of code that will be executed after a try/catch block. The finally block will execute whether or not an exception is thrown. Even there is a return statement in the try block, the finally block executes right after the return statement is encountered,and before the return is executes.

Therefore,finally block is the right place to close your files, release the network sockets and perform any other clean up requires. If the try block executes with no exceptions, the finally block executes immediately  after the try block completes. In case there was exception is thrown in try block,then finally block executes immediately after the proper catch block completes.

Syntax:

try{
// you need to write code in this block there is possibility of raised exceptions
}
catch(MyFirstException)

{
//put the code here that handles this exception
}
finally
{
//put the code here to release any resource  we allocated in try block

}

Example:

try{
//open database connection

//read the data
}
catch(MyFirstExcetpion e)

{
}
finally
{
//close the connection
}


Example 1:

try{
System.out.println("try");
}
catch(ArithmeticException ae)
{
System.out.println("catch");
}
finally
{
System.out.println("finally");
}

Output:
try
finally 

In the above program normal termination happens

Example 2:

try
{
System.out.println(10/0);
}
catch(ArithmeticException ae)
{
System.out.println("catch");
}
finally

{
System.out.println("finally");
}

Output:
catch
finally

In the above program also happens normal termination only

Example 3:

try
{
System.out.println(10/0);
}
catch(NullPointerException ne)
{
System.out.println("catch");
}
finally

{
System.out.println("finally");
}

Output:
finally

This program was terminated abnormally

Hence finally block should always execute irrespective of whether the execution is raised or not raised or handled or not handled.
The finally block won’t be executed if the system it self exists(JVM shutdown) i.e in the case of System.exit() finally block won’t be executed.

Recommended to Read More Topics:
MVC Architecture in Java
When to use abstract class and when interface in Java
How cookies works in servlet
IT Basics for Tech Developers


Example:
try
{
System.out.println("How are u?");
System.exit(0);
}
catch (ArithmeticException e)
{
System.out.println("catch");
}
finally
{
System.out.println("finally");

}

Output:
How are u?



Monday, November 16, 2015

Exception handling in java with example

In this post you will understand and learn Exception Handling in Java. This is one of the core concept in Java. As a programming developer must have strong knowledge on exceptions handling in java. In previous post i have written Top 10 exceptions in java,recommended go through this link as well to aware of various exceptions in java.

 

Exception:

  • An Exception can be anything which interrupts normal flow of the Program.
  • It is an unexpected unwanted event which disturbs entire flow of the program
  • If we are not handling exception, the program may terminate abnormally.
  • This is not a graceful termination
  • Being a good programming practice we should handle exceptions  for graceful termination of the program

Reasons for exception:

  • Fallowing situation can cause an exception
  • Try to opening non-existing files
  • Network connection problem
  • class file missing which was supposed to be loaded and so on

Difference between error and Exception:

 


Advantages of Exception Handling:

  1. Exception Handling allows us to control normal flow of the program by using Exception handling in the  program
  2. Exception normally disrupts normal flow of the program that is why we use exception handling
Example:

Statement 1;
statement 2;
statement 3;
statement 4;//exception occurs
statement 5;
statement 6;
statement 7;

Suppose there is 7 statements in your program  and there occurs exception at statement 4,rest of the code will not be executed. statement 5 to statement 7 will not run. If we perform exception handling the rest of the code will be executed. That is why we use exception handling in java.

Exception class Hierarchy:


Types of Exceptions:

There are mainly two types of exceptions. They are

1) Checked Exception
2) Unchecked Exception

Checked Exceptions:

 The Exceptions which are checked by the compiler for smooth execution of the program
at runtime are called "Checked exception"

Examples:  IOException, InterruptedException, ServletException


Unchecked Exceptions:

The Exceptions which are unable to checked by the compiler is called "Unchecked exception".Runtime Exceptions are also known as unchecked exception

Examples:  ArithmeticException, ArrayIndexOutOfBoundException, NullPointerException

Recommended to read : TOP 10 Exceptions in java

java Exception Handling:

There are 5 keywords are used in java exception handling
  1. try
  2. catch
  3. finally
  4. throw
  5. throws

try block:

  •     we have to place the risky code inside the try block and the corresponding exception
handling code inside the catch block
  • It must be used within the method
  • java try block must be fallowed by either catch block or finally block

Syntax for try block:

try{
 // risky code that means may throw exception
   }catch(Exception class-name  ref)
{
}

Catch block:  

  • Java catch block is used to handle the exception.
  • It must be used after the try block only
  • you can use multiple catch block within single try block

Without Exception Handling Code:

Ex:
class Test{
public static void main(String args[]){
System.out.println("Statement1");
System.out.println(10/0);
System.out.println("statement2");
  }
}
output:

Abnormal termination


Solution by Exception Handling:

Ex:    
class Test{
public static void main(String args[]){
System.out.println("Statement1");
try{
System.out.println(10/0);
} 
catch(ArithmetichException ae){
System.out.println(10/2);
}  
System.out.println("statement2");
}
}

Output:   
Normal Termination


Try with multiple catch blocks:

  • The way of handling exception is valid from exception to exception
  • Hence for every exception we should define corresponding catch blocks
  • Hence try with multiple catch block is possible
 try{
 // risky code
 } 
catch(ArithmeticException ae){
 // handling to Arithmetic Exception
 }
 catch(NullPointerException npe){
 //handling Nullpointer Exception
 }
catch(IOException ioe)
{
// handling IOException
}
catch(Exception e)
{
 //handling Exception
}

Finally:

  • It is not recommended to place clean up code inside try block  because there is no guarantee for execution of all statements inside try block
  • It is not recommended to maintain clean up code inside catch block because if there is no execution the catch block will not be executed
  • we required a block to maintain clean up code which should execute always irrespective of whether exception is raised or not whether it is handle or not. such block is nothing but"finally block"
  • Hence the main objective of finally block is to maintain clean up code
EX:

try{
//open the database connection
// read the data
catch(X e)
{
}
finally{
// close the connection
}


I hope you enjoy this post and share this to your friends and social website to reach more people. Keep follow me for latest updates and let me know your comments about this concept.







 

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...