Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Subject: Programming with Java (102044502)

Unit 3: Inner Class, Package, Exception Handing


Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

1. Inner Class
1.1. Class inside Class
• It is possible to define a class within another class; such classes are known as nested
classes.
• The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B
is defined within class A, then B is known to A, but not outside of A.
• A nested class has access to the members, including private members, of the class in
which it is nested. However, the enclosing class does not have access to the members of
the nested class.
• There are two types of nested classes: static and non-static. A static nested class is one
which has the static modifier applied. Because it is static, it must access the members of
its enclosing class through an object. That is, it cannot refer to members of its enclosing
class directly. Because of this restriction, static nested classes are seldom used.
• The most important type of nested class is the inner class.
• An inner class is a non-static nested class. It has access to all of the variables and methods
of its outer class and may refer to them directly in the same way that other non-static
members of the outer class do. Thus, an inner class is fully within the scope of its
enclosing class.

Example.
// Demonstrate an inner class.
class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display()
{
System.out.println("display: outer_x = " + outer_x);

class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
1
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

outer.test();
}
}

• An inner class has access to all of the members of its enclosing class, but the reverse is not
true. Members of the inner class are known only within the scope of the inner class and may
not be used by the outer class.

Example:
class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}

// this is an inner class


class Inner
{
int y = 10; // y is local to Inner
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}

void showy() {
System.out.println(y); // error, y not known here!
}
}

class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}

2
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

1.2. method local inner class


• Inner class can be defined within method of outer class

class Outer {
int outer_x = 100;
void test()
{
for(int i=0; i<10; i++) {

class Inner {

void display() {

System.out.println("display: outer_x = " + outer_x);


}
}

Inner inner = new Inner();

inner.display();
}
}
}
class InnerClassDemo {
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}

1.3. anonymous inner class


• Java anonymous inner class is an inner class without a name and for which only a single object
is created.
• In simple words, a class that has no name is known as an anonymous inner class in Java. It
should be used if you have to override a method of class or interface.

3
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

• Anonymous class using interface

// Java program to demonstrate Need for


// Anonymous Inner class

// Interface
interface Age {

// Defining variables and methods


int x = 21;
void getAge();
}

// Class 1
// Helper class implementing methods of Age Interface
class MyClass implements Age {

// Overriding getAge() method


public void getAge()
{
// Print statement
System.out.print("Age is " + x);
}
}

// Class 2
// Main class
// AnonymousDemo
class GFG {
// Main driver method
public static void main(String[] args)
{
// Class 1 is implementation class of Age interface
MyClass obj = new MyClass();

// calling getage() method implemented at Class1


// inside main() method
obj.getAge();
}
}

In the above program, interface Age is created with getAge() method and x=21. Myclass is
written as an implementation class of Age interface. As done in Program, there is no need to

4
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

write a separate class Myclass. Instead, directly copy the code of Myclass into this
parameter, as shown here:

// Java Program to Demonstrate Anonymous inner class

// Interface
interface Age {
int x = 21;
void getAge();
}

// Main class
class AnonymousDemo {

// Main driver method


public static void main(String[] args)
{

// Myclass is hidden inner class of Age interface


// whose name is not written but an object to it
// is created.
Age oj1 = new Age() {

public void getAge()


{
// printing age
System.out.print("Age is " + x);
}
};

oj1.getAge();
}
}

• Anonymous class using abstract class

abstract class Person{


abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
5
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

};
p.eat();
}
}

2. Package
2.1. Use of Package
• Packages are containers for classes that are used to keep the class name space
compartmentalized. For example, a package allows you to create a class named List, which
you can store in your own package without concern that it will collide with some other class
named List stored elsewhere. Packages are stored in a hierarchical manner and are explicitly
imported into new class definitions.
• The package is both a naming and a visibility control mechanism.
• You can define classes inside a package that are not accessible by code outside that package.
• You can also define class members that are only exposed to other members of the same
package.
• Defining a package
o To create a package is quite easy: simply include a package command as the first
statement in a Java source file. The package statement defines a name space in which
classes are stored.

package pkg;

o
If you omit the package statement, the class names are put into the default package,
which has no name.
o Command
▪ Javac –d . [filename].java
▪ java package2.[filecontaining main method]
o d
2.2. CLASSPATH
• How does the Java run-time system know where to look for packages that you create?
o First, by default, the Java run-time system uses the current working directory as
its starting point. Thus, if your package is in the current directory, or a
subdirectory of the current directory, it will be found.
o Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
o package MyPack;
▪ In order for a program to find MyPack, one of two things must be true.
Either the program is executed from a directory immediately above
MyPack, or CLASSPATH must be set to include the path to MyPack.
▪ The easiest way to try the examples shown in this book is to simply
create the package directories below your current development
directory, put the .class files into IT.
6
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

2.3. Import statements


• There are no core Java classes in the unnamed default package; all of the standard
classes are stored in some named package.
• Java includes the import statement to bring certain classes, or entire packages, into
visibility.
o import java.util.Date;
o import java.io.*;
2.4. Access control
• Refer UNIT-1

3. Exception Handing
3.1. Exception and Error
• The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
• A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code.
• When an exceptional condition arises, an object representing that exception is created
and thrown in the method that caused the error.
• Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code.
o Exceptions thrown by Java relate to fundamental errors that violate the rules of
the Java language or the constraints of the Java execution environment.
o Manually generated exceptions are typically used to report some error condition
to the caller of a method.
• Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.

try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...

finally {
// block of code to be executed before try block ends
}
• Exception Types
o All exception types are subclasses of the built-in class Throwable.
o Throwable is at the top of the exception class hierarchy.

7
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

o One branch is headed by Exception. This class is used for exceptional conditions
that user programs should catch. There is an important subclass of Exception,
called RuntimeException. Exceptions of this type are automatically defined for
the programs that you write and include things such as division by zero and
invalid array indexing.

o Types of Java Exceptions


▪ There are mainly two types of exceptions: checked and unchecked. An
error is considered as the unchecked exception. However, according to
Oracle, there are three types of exceptions namely:
▪ Checked Exception
• The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.
For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
▪ Unchecked Exception

8
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

• The classes that inherit the RuntimeException are known as


unchecked exceptions. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but
they are checked at runtime.
▪ Error
• Error is irrecoverable. Some example of errors are
OutOfMemoryError, VirtualMachineError, AssertionError etc.

3.2. use of try


o Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
o If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute. So, it is recommended not to keep the code in try block that will
not throw an exception.
o Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw an exception
}finally{}
3.3. Catch
o Java catch block is used to handle the Exception by declaring the type of exception within
the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception.
o The catch block must be used after the try block only. You can use multiple catch block
with a single try block.
o The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.

o But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.

9
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.

public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception

System.out.println("rest of the code");


}

}
Output: Exception in thread "main" java.lang.ArithmeticException: / by zero

Solution by exception handling


Let's see the solution of the above problem by a java try-catch block.

10
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

Output:
java.lang.ArithmeticException: / by zero
rest of the code

Example:
public class TryCatchExample9 {

public static void main(String[] args) {


try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

o Java Multi-catch block


o A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence
of different exceptions, use java multi-catch block.
o At a time only one exception occurs and at a time only one catch block is executed.

11
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Example:
public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");

12
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

}
}

Output:
Arithmetic Exception occurs
rest of the code

public class MultipleCatchBlock2 {

public static void main(String[] args) {

try{
int a[]=new int[5];

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code

o In this example, try block contains two exceptions. But at a time only one exception occurs and
its corresponding catch block is executed.
public class MultipleCatchBlock3 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;

13
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:
Arithmetic Exception occurs
rest of the code

o In this example, we generate NullPointerException, but didn't provide the corresponding


exception type. In such case, the catch block containing the parent exception class Exception will
invoked.

public class MultipleCatchBlock4 {

public static void main(String[] args) {

try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");

14
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

}
System.out.println("rest of the code");
}
}

Output:
Parent Exception occurs
rest of the code

o Let's see an example, to handle the exception without maintaining the order of exceptions (i.e.
from most specific to most general).

class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}

Output:
Compile-time error

3.4. Throw
• The Java throw keyword is used to throw an exception explicitly.
• We can throw either checked or unchecked exceptions in Java by throw keyword. It is
mainly used to throw a custom exception. We will discuss custom exceptions later in this
section.
• The syntax of the Java throw keyword is given below.
o throw Instance i.e.,

throw new exception_class("error message");

• In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.

Example:

public class TestThrow1 {


//function to check if person is eligible to vote or not
15
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

public static void validate(int age) {


if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}

Output:
Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to vote
at TestThrow1.validate(TestThrow1.java:6)
at TestThrow1.main(TestThrow1.java:15)

3.5. throws and finally


• throws
o The Java throws keyword is used to declare an exception.
o It gives an information to the programmer that there may occur an exception.
So, it is better for the programmer to provide the exception handling code so
that the normal flow of the program can be maintained.
o Syntax of Java throws

return_type method_name() throws exception_class_name{


//method code
}

o Example
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
16
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

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...

• Finally
o Java finally block is always executed whether an exception is handled or not.
Therefore, it contains all the necessary statements that need to be printed
regardless of the exception occurs or not.
o Java finally block is a block used to execute important code such as closing the
connection, etc.

17
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

o Use cases of finally


▪ Case-1 : When an exception does not occur

class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of phe code...");


}
}

Output:
finally block is always executed
rest of the code...

▪ Case-2: When an exception occurr but not handled by the catch block

public class TestFinallyBlock1{


public static void main(String args[]){

try {

System.out.println("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
18
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}

Output:
Inside the try block
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestFinallyBlock1.main(TestFinallyBlock1.java:9)

Here, the finally block is executed after the try block and then the
program terminates abnormally.

▪ Case-3: When an exception occurs and is handled by the catch block


public class TestFinallyBlock2{
public static void main(String args[]){

try {

System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


19
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

}
}

Output:
Inside try block
Exception handled
java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...
3.6. Built in Exception
• Refer Types of exception(subtopic) of topic 3.1
3.7. Custom exception
• In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception.
• Why use custom exceptions?
o Java exceptions cover almost all the general type of exceptions that may occur
in the programming. However, we sometimes need to create custom exceptions.
o Following are few of the reasons to use custom exceptions:
▪ To catch and provide specific treatment to a subset of existing Java
exceptions.
▪ Business logic exceptions: These are the exceptions related to business
logic and workflow. It is useful for the application users or the developers
to understand the exact problem.
o In order to create custom exception, we need to extend Exception class that
belongs to java.lang package.
o Syntax

public class WrongFileNameException extends Exception {


public WrongFileNameException(String errorMessage) {
super(errorMessage);
}
}

• Example:

// class representing custom exception


class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException

20
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

public class TestCustomException1


{

// method to check the age


static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}

Output:
Caught the exception
Exception occured: InvalidAgeException: age is not valid to vote
rest of the code...

21
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

3.8. Throwable Class: Visit topic 3.1

3.9. Run-time Stack mechanism in Java


• For every thread, JVM (Java virtual machine) creates a run-time stack.
o Each and every call performed in a thread is stored in the stack.
o Each entry in the run-time stack is known as an activation record or stack
frame.
o After completing every method call by the thread is removed from the
corresponding entry of the stack.
o After completing all the methods, the stack will be empty and that run-time
stack will be destroyed by the JVM before terminating the thread.

22
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

class ADIT {
public static void main(String[] args)
{
fun();
}

public static void fun()


{
moreFun();
}

public static void moreFun()


{
System.out.println("Hello CP!");
}
}
• Construction of run-time Stack For normal termination:
▪ Firstly, the main thread will call the main() method, and the
corresponding entry will be in the stack.
▪ After that main() method is called the fun() method, which will store in
the stack.
▪ In the fun() method, moreFun() method is called. Therefore at last
moreFun() will be stored in the stack.
▪ Finally, moreFun() is not calling any method and it will print Hello CP!

23
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

• Construction of run-time Stack For abnormal termination:

public class ExceptionHandling {


public static void main(String[] args)
{
fun();
}
public static void fun()
{
moreFun();
System.out.println("Method fun");
}
public static void moreFun()
{
System.out.println(10 / 0);
System.out.println("Method moreFun");
}
}
▪ The example above has ArithmeticException at method moreFun() location, the
JVM will check any exception handling code is there. If not, then method
moreFun() will be responsible to create exception objects because exceptions
are raised on method moreFun() and corresponding entry from the stack will be
removed and the control goes to method fun().
▪ JVM again go to the caller method to check if it is having any exception handling
code are not. If not JVM terminates the method abnormally and deleted the
corresponding entry from the stack.
▪ The above process continues until the main thread. If the main thread(main
method) doesn’t have any exception handling code the JVM also terminates the
main method abnormally and the default exception handler is responsible to
print the exception message to the output screen which is the part of JVM.

3.10. Nested try


• In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception
is pushed onto the stack.
• For example, the inner try block can be used to handle
ArrayIndexOutOfBoundsException while the outer try block can handle the
ArithemeticException (division by zero).

24
Subject: Programming with Java (102044502)
Unit 3: Inner Class, Package, Exception Handing
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH

Example:
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}

System.out.println("normal flow..");
}
}
Output:
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
other statement
normal flow..

25

You might also like