Java Exception Handling

[java title=”ExceptionExample.java” gutter=”true” highlight=”5″]
package com.sample;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ExceptionExample {

public static void main(String[] args) {

// The following line will issue an exception and the execution will
// stop

// int temp = 1 / 0;

// System.out.println(" This line will NOT be printed ");
// This line will not be printed because the execution has stopped at
// line number
// 16 , because of divide by zero exception;

try {

int i = 1 / 0;
int j = 1 / 0;
System.out.println ( " I will NOT be printed " );
} catch (Exception e) {

System.out.println(" Exception is " + e);
}
// With this code, you would NOT understand if the exception happened at
// line 23 or line 24 if you just print out the exception

// Instead, print out the stack trace for a more meaningful and complete
// message

try {

int i = 1 / 0;
int j = 1 / 0;
} catch (Exception e) {
System.out.println("Full Stack Trace of the Error");
e.printStackTrace();
}

// The code will continue to execute after the catch as well
System.out.println("The Program execution continues even after catch");

// There can be more than one catch block
// The generic Exception class should always be caught at the end
// The generic "Exception" class is a "Catch All" kind of a Class
// that can catch any exception
// Other Exceptions like IOException are sub-classes of the "Exception" class
// In this case, FileNotFoundException is a sub-class of IOException

try {

int i = 1 / 0;
FileReader fr = new FileReader("read_text.txt");

}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println(" Exception is File " + e);
}
catch (Exception e) {
System.out.println(" Exception is " + e);

}

// What if you want to do something after catching the exception ?
// Let’s say, irrespective of the exception type ( File or Arithmetic )
// You want to finally close all FileReader Objects if they are open
// Instead of replicating the code in all ‘catch’ blocks, you can
// just write a finally block.

// ‘finally’ is Optional

FileReader fr = null;
try {

int i = 1 / 0;
fr = new FileReader("read_text.txt");

}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println(" Exception is File " + e);
}
catch (Exception e1) {
System.out.println(" Exception is " + e1);

}
finally
{
try{
fr.close();
}
catch (IOException e) {
e.printStackTrace();
}
}

// In the finally block above, the method fr.close()
// will also throw a IOException. What will you do then ?

// There are 2 choices ?
//    1. make the whole method ( In this case main () ) as throwable
// syntax is ‘public static void main(String[] args) throws IOException’
// OR 2 . enclose the finally block in a try catch block as follows
// finally
// {
//    try{
//          fr.close();
//      }
//    catch (IOException e) {
//      e.printStackTrace();
//    }
// }

// Now that we have some idea on what exceptions are and how the code
// flow happens, let’s talk about the types of exceptions
// There are 2 Types of Exceptions
// 1. Checked Exceptions
// 2. Unchecked Exceptions

// We have seen examples of Checked Exceptions until now
// 1. They are all sub-classes of the parent class java.lang.Exception
// 2. They should be Handled or Thrown to the Caller
// The Thumb rule is –
// If you can guess the Exception at compile time, its a ‘Checked Exception’

// Unchecked exceptions
// 1. sub-classes of ‘java.lang.RuntimeException’
// 2. You need NOT handle or throw to the Caller
// The thumb rule is –
// If you can’t guess the exception at compile time, its a ‘Unchecked Exception’
// Examples – java.lang.OutOfMemoryError , java.lang.NullPointerException

try{

String str = null;
System.out.println( " The length of the string is " + str.length());
}

catch( NullPointerException e)
{
System.out.println("Exception is " + e);
}
finally
{
System.out.println( " Do I get executed ?");
}

String str = null;
System.out.println( " The length of the string is " + str.length());
System.out.println( " I don’t get executed" );

// throw vs throws

// You can ‘throw’ an exception explicitly
// Any code can ‘throw’ an exception
// You ‘throw’ an exception, if you do NOT want to handle it there

// Discuss scenarios of when to ‘throw’ an exception.

// when you want to declare that a method throws an exception use throws
// eg., public void method () throws IOException
// or   public FileReader getFileReader () throws FileNotFoundException

// In the following class FileNotFoundExceptionExample
// The method getFileReader() throws the FileNotFoundException
// since it is not being handled there
// So, when you want to use that class, you would have to explicitly
// handle it yourself.

FileReaderExample fre = new FileReaderExample();

// If you write the following line, your compilation error will be
// Unhandled Exception Type….
// fre.getFileReader("File1");
// Instead, write it within a try catch block and handle the
// FileNotFoundException

try
{
fre.getFileReader("file1");
}
catch ( FileNotFoundException fe)
{
fe.printStackTrace();
}

// You can also create a new Exception Class if required.
// In your Java Training class, we will discuss scenarios as to,
// when you would create your own Custom Exception Classes
// As a good practice, almost always your custom Exception Classes should end
// with the word Exception
// Eg., ObjectNotFoundException , ConcatenationException etc.

ConcatenateClass cc = new ConcatenateClass ("Siva", "Nalavenkata");

// The following line without a try catch block will give compile time error
// since we are explicitly defining the Concatenate () class as throwing
// an exception
// Look at the definition .. public String Concatenate () throws ConcatenationException
// cc.Concatenate();

try
{
cc.Concatenate();
}
catch( ConcatenationException ce)
{
System.out.println (ce);
}

}

}

class FileReaderExample
{
FileReader fr;

public FileReader getFileReader ( String file) throws FileNotFoundException
{
try
{
fr = new FileReader(file);
return fr;
}
catch (FileNotFoundException f) {
throw new FileNotFoundException();
}
}

}

class ConcatenateClass
{
String str1 ;
String str2 ;

public ConcatenateClass (String str1 , String str2 )
{
this.str1 = str1;
this.str2 = str2;
}

public String Concatenate () throws ConcatenationException
{
if ( ( str1 == null ) && ( str2 == null ))
{
throw new ConcatenationException (" Both the Strings are NULL. Cannot Concatenate");
}
return str1.concat(str2);
}
}

class ConcatenationException extends Exception
{
String exception;

public ConcatenationException ()
{
exception = "";
}

public ConcatenationException ( String str)
{
exception = str;
}

public String toString()
{
return exception;
}

}

[/java]

Questions

  • Do you have to always use the finally block in Java ?
  • What are the types of Exceptions ?
  • What is the base class for all Java Exceptions ?
Advertisements

One thought on “Java Exception Handling

  1. Merri says:

    I read a lot of interesting articles here.
    Probably you spend a lot of time writing, i know how to
    save you a lot of time, there is an online tool that creates readable, SEO friendly articles in seconds, just search in google – laranitas free content source

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s