Tag Archives: Java Tutorial

Java Tutorial : The Nested try catch Block

The nested try-catch block is used to handle exceptions in Java applications. You can enclose a try-catch block in an existing try-catch block. The enclosed try-catch block is called the inner try-catch block, and the enclosing block is called the outer trycatch block. If the inner try block does not contain the catch statement to handle an exception then the catch statement in the outer block is checked for the exception handler. The following syntax shows how to create a nested try-catch block:

class SuperClass
{
public static void main(String a[])
{
<code>;
try
{
<code>;
try
{
<code>;
}
catch( <var>)
{
<code>;
}
}
catch( <var>)
{
<code>;
}
}
}

Java Tutorial : The super and this Keywords

Java provides the super keyword that enables a subclass to refer to its superclass. The super keyword is used to access:

  • superclass constructors
  • superclass methods and variables

Consider a Java application, which consists of multiple classes. The subclass in the application needs to reuse the constructor of the superclass. In this application, super keyword is used as a method and invokes the constructor of its immediate superclass. The syntax to invoke the constructor of a superclass using the super() method is:

super (<parameter1>, <parameter 2>,..,<parameterN>);

In the above syntax, <parameter1>, <parameter 2>,..,<parameterN> refer to the list of parameters that you need to pass to the constructor of the superclass.

If no parameters are passed to the super() method, it invokes the default constructor of the superclass. If the superclass contains the overloaded constructor, you can pass parameters to the super() method to invoke a particular constructor. When you use the super() method in the constructor of the subclass, it should be the first executable statement in the constructor.

Consider a Java application, in which both, superclass and subclass, have member variables with the same name. In this application, the super keyword is used to access the member variables of the superclass. The syntax to access the member variable of a superclass is:

super.<variable>;

The subclass can also access the member methods of the superclass using the super keyword. The following code snippet shows the Literature subclass accessing the member variable of the Book superclass:

class Book
{
int categoryCode;
}
class Literature extends Book
{
int categoryCode;
public void input(int c1, int c2)
{
super.categoryCode=c1;
categoryCode=c2;
}
}

In the above code snippet, the Book class contains the categoryCode variable to store the category of a book, such as literature, science, fiction, suspense, and history. The Literature class also contains the categoryCode variable to store the subcategory of a book. For example for literature category, the subcategories are English, French, Hindi, and Russian. The input() method accepts two values for c1 and c2 variables. The value that you pass for c1 variable is assigned to the superclass variable whereas the value of the c2 variable is assigned to the subclass variable. The this keyword is used to refer to the current object. You can use the this keyword when a method defined in a Java class needs to refer to the object used to invoke that method, as shown in the following code snippet:

Book(int bcode, double bprice)
{
this.bookCode=bcode;
this.bookPrice=bprice;
}

In the above code snippet, the this keyword refers to the object that invokes the Book() constructor.

Another situation where you can use the this keyword is when the local and instance variables have the same name. For example, the Book class has two member variables, bookCode and bookPrice. The constructor of the Book class is used to initialize its member. If the formal parameters passed to the constructor have the same name as instance variables, you need to use the this keyword to refer to the
instance variables. The following code snippet shows how to use the this keyword when instance and formal parameters have the same name:

Book(int bcode, double bprice)
{
this.bcode=bcode;
this.bprice=bprice;
}

In the above code snippet, this keyword refers to the instance variables, bcode and bprice. The values of the formal parameters, bcode and bprice of the Book() constructor are assigned to the instance variables.

In addition, you can use the this keyword in a constructor of a class to invoke another constructor of the class. Unlike the super keyword, the this keyword can invoke the constructor of the same class. The following code snippet shows how to invoke a constructor using the this keyword:

class Book
{
public Book(String bname)
{
this(bname, 1001);
}
public Book(String bname, int bcode)
{
bookName=bname;
bookCode=bcode;
}
}

Java Tutorial : Implementing Interfaces – Example

David Johnson is the owner of Safest Software Co. that deals in buying and selling of hardware and software computer products. Don Allen, an employee of the Safest Software Co. is assigned the task to develop a Java application to keep track of the inventory of the computer hardware and software products.

The application consists of an interface, ItemCount that includes the declaration of methods to be used in the superclass and subclass. The application includes the SoftwareProducts class that accepts the number of software items and calculates the
number.

The HardwareProducts class is included to accept the number of hardware items and to calculate the number. The Products class is included to create objects for the SoftwareProducts and HardwareProducts classes.
You can use the following code to create the ItemCount interface in Java:

interface ItemCount //Defining the interface.
{
//Defining abstract methods in the Billing interface.
public void noOfItems();
}

In the preceding code, the ItemCount interface contains the noOfItems() abstract method that needs to be implemented in the classes that implement the ItemCount interface.
You can use the following code to create the SoftwareProducts superclass:

class SoftwareProducts implements ItemCount
{
// Defining the data members.
int os= 60;
int oracle = 20;
int jav = 15;
int tot;
//Defining the methods.
public void calculate()
{
tot = os + oracle + jav;
}
public void noOfItems() // Method declared publicly in the interface.
{
System.out.println();
System.out.println(” “+”Total number of software products purchased is :
“+ tot);}
}

In the preceding code, the SoftwareProducts superclass defines the data members, os, oracle, and jav and the methods, calculate() and noOfItems(). These data members store the number of software products, Operating System, Oracle, and Java. The noOfItems() method displays the total number of the software items purchased by David.
You can use the following code to create the HardwareProducts class:

class HardwareProducts implements ItemCount
{
// Defining the data members.
int printer = 20;
int speaker = 12;
int harddisk = 25;
int htot;
public void calculate1()
{
htot = printer + speaker + harddisk;
}
public void noOfItems()// The method is declared publicly in the
interface, Billing.
{
System.out.println();
System.out.println(” “+”Total number of hardware items purchased is : ”
+htot);
}}
class Products
{
public static void main(String args[])
{
//Creating an object of the class, Hardware.
SoftwareProducts s = new SoftwareProducts();
HardwareProducts h = new HardwareProducts();
s.calculate();
h.calculate1();
s.noOfItems();
h.noOfItems();
}}

In the preceding code, the HardwareProducts subclass implements the ItemCount interface. The HardwareProducts class defines the data members, such as printer, speaker, and hard disk. These data members store the number of printer, speaker, and hard disk. The HardwareProducts class defines the calculate1() method to calculate the total number of hardware items. The noOfItems() method displays the total number of hardware items purchased by David.
The following figure shows the output of the preceding code:

implementing inheritance example

Using Interface to Display the Number of Items Purchased

Interfaces also enable you to declare constants that can be imported into multiple classes. The constant values declared in an interface can be implemented in any class. The constants defined in an interface are declared using the final keyword. You can use the following code to create the TBooks interface in Java:

interface TBooks
{
//Defining constants in an interface.
final int cd =10;
final int book =5;
}

In the preceding code, the TBooks interface declares a set of constants that stores the number of books and Compact Discs (CD) purchased.
You can use the following code to create the Dcd class:

class Dcd implements TBooks
{
void display()
{
System.out.println(” “);
System.out.println(“t The number of purchased CD’s are :” + cd);
System.out.println(” “);
}
}
In the preceding code, the Dcd class implements the TBooks interface to display the
number of purchased CDs.
You can use the following code to create the DBooks class:
class DBooks extends Dcd implements TBooks
{
void display1()
{
System.out.println(“t The number of purchased books are :” + book);
System.out.println(“t The number of purchased CD’s are :” + cd);
System.out.println(” “);
}
public static void main (String args[])
{
// Creating an instance of DBooks class.
DBooks db = new DBooks();
TBooks t;
t = db;
db.display1();
}}

In the preceding code, the DBooks subclass extends from the Dcd superclass and implements the TBooks interface. The display1() method displays the number of purchased books and CDs using inheritance.
The following figure shows the output of the preceding code:

implementing inheritance example 2

Number of Purchased CDs and Books

Java Tutorial : Throwing An Exception – Part 2

Printing a Stack Trace

When an exception is caught, you can find out the method or the line of the code where the exception is raised by using the printStackTrace() method. You can call the printStackTrace() method for printing the stack trace. The objects of the Throwable class inherit the stack trace. You can use the following code to print the stack trace for the ArithmeticException exception:

class PrintStack
{
public static void main(String args[])
{
int Num1= 30 , Num2 = 0;
try
{
int Num3=Num1/Num2;
}
catch(ArithmeticException obj)
{
obj.printStackTrace();
}
}
}

In the preceding code, printStackTrace() method is used to print the stack trace to check the line in the code where the exception is raised.

Using the printStackTrace Statement

Using the printStackTrace Statement

The output of the preceding code is:

Rethrowing an Exception

A catch block can rethrow an exception without handling it by using the throw statement. Exceptions are rethrown if a method causing the error wants to pass the error handling responsibilities to the exception-handlers in some other methods. You can use the following code snippet to rethrow an exception:

catch(Exception e)
{
System.out.println(“Exception Raised”);
throw e;
}

The exception goes to the catch block of the next higher context ignoring the catch blocks of the same try block.

You can use the following code to catch the NullPointerException and rethrow the exception to the outer handler:

class RethrowException
{
static void throwDemo()
{
try
{
throw new NullPointerException (“My Exception”);
}
catch(NullPointerException e)
{
System.out.println(“Exception caught in throwDemo()
method”);
throw e; // Rethrow the Exception.
}
}
public static void main(String args[])
{
try
{
throwDemo();
}
catch(NullPointerException e)
{
System.out.println(“Exception caught:” + e);
}
}
}

In the preceding code, the catch block in the throwDemo() method rethrows the NullPointer exception to the catch block defined in the main() method. The output of the preceding code is:

Rethrowing an Exception

Rethrowing an Exception

Using the throws Statement

The throws statement is used by a method to specify the types of exceptions the method throws. If a method is capable of raising an exception that it does not handle, the method must specify that the exception have to be handled by the calling method. This is done using the throws statement. The throws clause lists the types of exceptions that a method might throw. The following syntax shows how to declare a method that specifies a throws clause:
[<access_specifier>] [<modifier>] <return_type> <method_name>
[<arg_list>] [throws <exception_list>]

You can use the following code to throw the ClassNotFoundException exception:

class NoClassexception
{
static void throwMethod()
{
System.out.println(“In throwMethod”);
throw new ClassNotFoundException();
}
public static void main(String args[])
{
throwMethod();
// no try and catch statements to handle the exception
}
}

In the preceding code, the code does not compile because the caller method throws an exception but does not catch the exception. You can compile the code by first declaring that the throwMethod() throws the ClassNotFoundException exception. In addition, the main() method must define the try-catch statements to catch the exception. You can use the following code to use the throws statement:

class ThrowsClass
{
static void throwMethod() throws ClassNotFoundException
{
System.out.println(“In throwMethod”);
throw new ClassNotFoundException();
}
public static void main(String args[])
{
try
{
throwMethod();
}
catch(ClassNotFoundException Obja)
{
System.out.println(“throwMethod has thrown an
Exception:” + Obja);
}
}
}

The output of the preceding code is:

Using the Throws Statement

Using the Throws Statement

Java Tutorial : Throwing An Exception – Part 1

You can throw an exception explicitly using the throw statement. For example, you need to throw an exception when a user enters a wrong loginID or password. The throws clause is used to list the types of exceptions that can be thrown during the execution of a method in a program.

Using the throw Statement

The throw statement causes termination of the normal flow of control of the Java code and stops the execution of the subsequent statements if an exception is thrown when the throw statement is executed. The throw clause transfers the control to the nearest catch block handling the type of exception object throws. If no such catch block exists, the program terminates. The throw statement accepts a single argument, which is an object of the Exception class.

The following syntax shows how to declare the throw statement:

throw ThrowableObj

In the preceding syntax, ThrowableObj is an object of the Throwable class or a subclass of the Throwable class, such as Exception class. The ThrowableObj object is created using the new operator. The Java compiler gives an error if the ThrowableObj object does not belong to a valid Exception class. You can use the following code to throw the IllegalStateException exception:

class ThrowStatement
{
static void throwDemo()
{
try
{
throw new IllegalStateException();
// creating and throwing an object of the
IllegalStateException class.
}
catch(NullPointerException objA)
{
System.out.println(“Not caught by catch block inside
throwDemo().”);
}
}
public static void main(String args[])
{
try
{
throwDemo();
}
catch(IllegalStateException objB)
{
// catching an object of the
IllegalStateException class.
System.out.println(” Exception Caught in :” + objB);
}
}
}

In the preceding code, the new operator is used to construct an object of IllegalStateException. In the throwDemo() method , an exception of the type IllegalStateException is thrown.

The output of the preceding code is:

Using the Throw Statement

Using the Throw Statement

Displaying the Description of an Exception

The built-in exception classes in Java have two types of constructors: one with no parameter and another with a String parameter that defines the exception. The String parameter that you pass to the constructor of an exception can be displayed when exception object is passed as an argument to the System.out.println() statement. The following code shows the use of constructor of the IlegalStateException with String parameter:

class ThrowClass
{
static void throwDemo()
{
try
{
throw new IllegalStateException(“MyException”);
}
catch(IllegalStateException objA)
{
System.out.println(“Caught:” + objA);
}
} // End of throwDemo() method.
public static void main(String args[])
{
throwDemo();
}
}// End of the ThrowClass.

In the preceding code, description added to the constructor of the IllegalStateException exception is displayed as MyException.

The output of the preceding code is:

Displaying the Description of an Exception

Displaying the Description of an Exception

Java Tutorial : Implementing Exception Handling – Part 2

Handling the Unreachable Code Problem

The multiple catch blocks generate unreachable code error. If the first catch block contains the Exception class object then the subsequent catch blocks are never executed. The Exception class being the superclass of all the exception classes catches various types of exceptions. The Java compiler gives an error stating that the subsequent catch blocks have not been reached. This is known as the unreachable code problem. To avoid unreachable code error, the last catch block in multiple catch blocks must contain the Exception class object.
The following code is an example of the unreachable code problem:

class UnreachableCodeDemo
{
public static void main(String args[])
{
int num1=5, num2=0, num3;
try
{
num3=num1/num2;
}
catch(Exception e)
{
System.out.println(“Error”);
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero.”);
//Unreachable catch statement.
}
}
}

In the preceding code, the Java compiler gives an error stating that the catch block handling ArithmeticException has not been reached. This is because the Exception class, being the base class for all exceptions, handles all the exceptions that are raised by the Java code in the very first catch block. The output of the preceding code is:

Unreachable Code Problem

Unreachable Code Problem

The unreachable code problem can be solved if the subclasses, such as ArithmeticException, ArrayIndexOutOfBounds, or NullPointerException in the multiple catch statements are written before the Exception superclass.

Using the finally Clause

When an exception is raised, the statements in the try block written after the statement in which the exception occurred are ignored. The finally block is used to process certain statements, no matter whether an exception is raised or not. The block of code attached with the finally clause is executed after a try-catch block has been executed. The following syntax shows how to declare the try-finally block:

try
{
// Block of code
}
finally
{
// Block of code that is always executed irrespective of an
exception being raised or not.
}

If there is a catch block associated with the try block, the finally clause is written after the catch block. The following syntax shows how to declare the try-catch-finally block:

try
{
// Block of code.
}
catch(execption1 obj1)
{
System.out.println(“Exception1 has been raised”);
}
catch(exception2 obj2)
{
System.out.println(“Exception2 has been raised”);
}
finally
{
// Block of code that is always executed irrespective of an
exception being raised or not.
}

The finally block executes whether or not an exception is raised. If an exception is thrown, the finally block executes even if no catch statement matches the exception. For example, a file has to be closed irrespective of whether an exception is raised or not. You can place the code to close the file in both the try and catch blocks.

To avoid duplication of code, you can place the code in the finally block. The following code snippet is used to write a try-catch block to declare methods to open and write to a file:

try
{
openFile();
writeFile(); // Might raise an exception.
}
catch(ExceptionName obj)
{
// Process the exception.
}
finally
{
closeFile();
}

In the preceding code, the finally clause is executed regardless of whether an exception is thrown or not. You can have only one finally block for an exceptionhandler. You can use the finally clause to execute the closeFile() method.

Java Tutorial : Implementing Exception Handling

When an unexpected error occurs in a method, Java creates an object of the type Exception. After creating the Exception object, Java sends it to the program by throwing the exception. The Exception object contains information about the type of error and the state of the program when the exception occurred. You need to handle the exception using an exception-handler and process the exception. You can implement exception-handling in a program by using the following keywords:

  • try
  • catch
  • throw
  • throws
  • finally

Using try and catch Statements

The try block encloses the statements that might raise an exception within it and defines the scope of the exception handlers associated with it. If an exception is raised within the try block, the appropriate exception-handler that is associated with the try block processes the exception.

In Java, the catch block is used as an exception-handler. You enclose the code that you want to monitor inside a try block to handle a run-time error. A try block must have at least one catch block that follows it immediately. The catch clause specifies the exception type that you need to catch. The following code shows an arithmetical exception with no exception being handled:

class UnhandledException
{
public static void main(String args[])
{
int num1=0, num2=5;
int num3=num2/num1;
System.out.println ("The num3 = " + num3);
}
}

In the preceding code, the default handler of the Java run-time system throws a raised exception when zero divides a number. It creates an object of the ArithmeticException exception class. The output of the preceding code is:

An Unhandled Exception

The output of the preceding code shows that the exception thrown is the object of the ArithmeticException subclass of the Exception class. The following syntax shows how to declare the try block:

try
{
// Statements that cause an exception.
}

If an exception is raised within a try block, the appropriate exception-handler that is associated with the try block handles the exception.

The catch statement takes the object of the Exception class that refers to the exception caught, as a parameter. When the exception is caught, the statements within the catch block are executed. The scope of the catch block is restricted to the statements in the preceding try block only. The following syntax shows how to declare the try- catch block:

try
{
// Statements that cause an exception.
}
catch(ExceptionName obj)
{
// Error handling code.
}

In the preceding syntax, the catch statement accepts the object of the Exception class that refers to the exception caught, as a parameter. When the exception is caught, the statements within the catch block are executed. You can use the following code to try and catch an arithmetic exception:

class ArithmeticExp
{
public static void main(String args[])
{
int num1=0, num2=5,num3=0;
1B.26 Programming in Java
try
{
num3=num2/num1;
System.out.println("The result=" + num3);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero is performed");
}
}
}

The output of the preceding code is:

Using Try-Catch Statements

 

Using Multiple catch Statements

A single try block can have many catch blocks. This is necessary when the try block has statements that raise different types of exceptions. The following code traps three types of exceptions:

public class TryCatch
{
public static void main(String args[])
{
int array[] = {0,0};
int num1, num2, result = 0;
num1 = 100;
num2 = 0;
try
{
result = num1/num2;
System.out.println(num1 / array[2]);
//more statements
}
catch(ArithmeticException e)
{
System.out.println("Error… Division by zero");
}
Programming in Java 1B.27
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error… Out of bounds");
}
catch (Exception e)
{
System.out.println("Some other error");
}
System.out.println("The result is: " + result);
//program proceeds
}
}

In the preceding code, the try block has many statements, each of which can result in an exception. Three catch blocks follow the try block, and each catch block handles a different type of exception.

The output of the preceding code is:

Using Multiple Catch Statements

Java Tutorial : Built-in Exceptions

The built-in exceptions in Java are categorized on the basis of whether the exception is handled by the Java compiler or not. Java consists of the following categories of built-in exceptions:

  • Checked Exceptions
  • Unchecked Exceptions

Checked Exceptions

Checked exceptions are the objects of the Exception class or any of its subclasses excluding the Runtime Exception class. Checked exceptions are the invalid conditions that occur in a Java program due to invalid user input, network connectivity problem, or database problems. For example, java.io.IOException is a checked exception. The IOException exception is thrown whenever an input/output operation is abnormally terminated.

Java uses the try-catch block to handle the checked exceptions. The statements within a program that throw an exception are placed in the try block. You associate an exception-handler with the try block by providing one or more catch handlers immediately after the try block.

The following table lists the various checked exceptions defined in the java.lang package:

Exception

Cause of Creation

ClassNotFoundException

Occurs when the Java run-time
system is unable to find the class
referred.

IllegalAccessException

Occurs when you want to refer a
class that is not accessible.

InstantiationException

Occurs when you try to create an
object of an abstract class or
interface.

NoSuchMethodException

Occurs when you call a method that
does not exist.

 

Unchecked Exceptions

Unchecked exceptions are the run-time errors that occur because of programming errors, such as invalid arguments passed to a public method. The Java compiler does not check the unchecked exceptions during program compilation. For example, if you divide a number by zero, an unchecked or run-time exception is raised.

The following table lists the various unchecked exceptions:

Exception

Cause of Creation

ArithmeticException

Occurs when you make an
arithmetic error, such as dividing a
number by zero.

ArrayIndexOutOfBoundsException

Occurs when an attempt is made
to access an array element beyond
the index of the array.

ArrayStoreException

Occurs when you assign an
element to an array that is not
compatible with the data type of
that array.

ClassCastException

Occurs when you assign a
reference variable of a class to an
incompatible reference variable of
another class.

IllegalArgumentException

Occurs when you pass an
argument of incompatible data
type to a method.

NegativeArraySizeException

Occurs when you create an array
with negative size.

NullPointerException

Occurs when an application tries to
use an object without allocating
memory to it or calls a method of
a null object.

NumberFormatException

Occurs when you want to convert
a string in an incorrect format to a
numeric format.

Java Tutorial : Exception Classes

Exception Handling

To handle exceptions, the Java run-time system searches for an exception-handler. In Java, a catch statement is an exception-handler that is used to handle an exception. The search for an exception-handler begins with the method in which the exception is raised. If no appropriate exception-handler is found, the Java run-time system searches the exception-handler in the next higher method hierarchy. The type of exception handled by the exception-handler should match the type of exception thrown. The Java run-time system proceeds with the normal execution of the program after an exception gets handled. If no appropriate exception-handler is found by the Java run-time system, the program is terminated.

In Java, the Throwable class is the superclass of all the exception classes. Object class is the base class of the exception hierarchy. The Exception class and the Error class are two subclasses of the Throwable class.

Exception Hierarchy

Exception Hierarchy

Throwable Class

The Throwable class is a subclass of the Object class. The Throwable class is the superclass of all the exception objects that are thrown in Java. You can throw only those exception objects that are derived from the Throwable class. The following syntax shows how to declare a constructor for the Throwable class:

Throwable()

In the preceding syntax, a new Throwable constructor with no arguments is created.

You can also declare a constructor for the Throwable class with a user-defined message. The following syntax shows how to declare a constructor of the Throwable class with a user-defined message:

Throwable(String message)

In the preceding syntax, message represents the specified message included in the Throwable class.

Exception Class

The Exception class has various subclasses, such as ClassNotFoundException, IllegalAccessException, and RuntimeException. The ClassNotFoundException exception is thrown when a class is being referred, but no definition for the class with the specified name is found. The IllegalAccessException exception is thrown when a particular method is not found. The RuntimeException exception handles the exceptions that are raised in the programs during run time.

Error Class

The Error class defines exceptions related to the Java run-time environment. For example, OutOfMemoryError is an error that occurs when there is insufficient system memory to execute a program. A program is abruptly aborted when an Error object is thrown. The Error class consists of two types of constructors, one without any error message and the other with an error message. The following syntax shows the constructor of the Error class with no message:

Error()

The following syntax shows the constructor of the Error class having information about the error:

Error(String message)

Java Tutorial : Exception Handling

The term exception in Java indicates an exceptional event. It can be defined as an abnormal event that occurs during program execution and disrupts the normal flow of instructions. The abnormal event can also be an error in the program.

Errors in a Java program are categorized into two groups: compile-time errors and run-time errors. Compile-time errors occur when you do not follow the syntax of a programming language. The compiler detects the syntax error of the program while compiling the program. For example in Java, you need to terminate every expression with a semicolon (;). If you do not follow this rule you get a compile time error.

Run-time errors occur during the execution of a program. For example, if the program runs out of memory, it results in run-time error.

Concept of Exceptions

An exception is a run-time error that occurs during the execution of a Java program. For example, if you divide a number by zero or open a file that does not exist, an exception is raised. In Java, exceptions can be handled either by the Java run-time system or by a user-defined code. When a run-time error occurs, an exception is thrown.

Error handling becomes a necessity when you develop applications that need to take care of unexpected situations. The unexpected situations that may occur during program execution are:

  1. Running out of memory
  2. Resource allocation errors
  3. Inability to find files
  4. Problems in network connectivity