[go: up one dir, main page]

0% found this document useful (0 votes)
85 views31 pages

Abstract Class Interface: Types of Packages: Built-In and User Defined

The document compares and contrasts abstract classes and interfaces in Java. It discusses: 1) Abstract classes can contain both abstract and non-abstract methods, while interfaces can only contain abstract methods. Interfaces can also contain default and static methods since Java 8. 2) Abstract classes do not support multiple inheritance but interfaces do. 3) Abstract classes can contain final, non-final, static and non-static variables, while interfaces can only contain static and final variables. The document provides examples of declaring an abstract class and interface.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views31 pages

Abstract Class Interface: Types of Packages: Built-In and User Defined

The document compares and contrasts abstract classes and interfaces in Java. It discusses: 1) Abstract classes can contain both abstract and non-abstract methods, while interfaces can only contain abstract methods. Interfaces can also contain default and static methods since Java 8. 2) Abstract classes do not support multiple inheritance but interfaces do. 3) Abstract classes can contain final, non-final, static and non-static variables, while interfaces can only contain static and final variables. The document provides examples of declaring an abstract class and interface.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only
abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non- Interface has only static and final
static variables. variables.

4) Abstract class can provide the implementation of Interface can't provide the
interface. implementation of abstract class.

5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare
interface.

6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

A package can be defined as a group of similar types of classes, interface, enumeration or


sub-package. Using package it becomes easier to locate the related classes and it also
provides a good structure for projects with hundreds of classes and other files.

Types of Packages: Built-in and User defined

 Built-in Package: Existing Java package for example java.lang, java.util etc.
 User-defined-package: Java package created by user to categorize their project's
classes and interface.
Creating a package

Creating a package in java is quite easy. Simply include a package command followed by
name of the package as the first statement in java source file.
package mypack;
public class employee
{
statement;
}
The above statement will create a package woth name mypack in the project directory.
Java uses file system directories to store packages. For example the .java file for any class
you define to be part of mypack package must be stored in a directory called mypack.
Additional points about package:

 A package is always defined as a separate folder having the same name as the
package name.
 Store all the classes in that package folder.
 All classes of the package which we wish to access outside the package must be
declared public.
 All classes within the package must have the package statement as its first line.
 All classes of the package must be compiled before use (So that they are error free)

Example of Java packages


//save as FirstProgram.java
package learnjava;
public class FirstProgram{
public static void main(String args[]) {
System.out.println("Welcome to package");
}
}

How to compile Java programs inside packages?


This is just like compiling a normal java program. If you are not using any IDE, you need to
follow the steps given below to successfully compile your packages:
javac -d directory javafilename
Example:
javac -d . FirstProgram.java
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like d:/abc (in case of windows) etc. If you want to keep the package
within the same directory, you can use . (dot).

How to run Java package program?


You need to use fully qualified name e.g. learnjava.FirstProgram etc to run the class.
To Compile:
javac -d . FirstProgram.java
To Run:
java learnjava.FirstProgram
Output: Welcome to package
import keyword
import keyword is used to import built-in and user-defined packages into your java source
file so that your class can refer to a class that is in another package by directly using its
name.
There are 3 different ways to refer to any class that is present in a different package:

1. Using fully qualified name (But this is not a good practice.)

If you use fully qualified name to import any class into your program, then only that
particular class of the package will be accessible in your program, other classes in the
same package will not be accessible. For this approach, there is no need to use
the import statement. But you will have to use the fully qualified name every time you
are accessing the class or the interface, which can look a little untidy if the package
name is long.

This is generally used when two packages have classes with same names. For
example: java.util and java.sql packages contain Date class.

Example :
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}

//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output:

Hello

2. To import only the class/classes you want to use

If you import packagename.classname then only the class with name classname in the
package with name packagename will be available for use.

Example :
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.A;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}

Output:

Hello

3. To import all the classes from a particular package


If you use packagename.*, then all the classes and interfaces of this package will be
accessible but the classes and interface inside the subpackages will not be available for
use.

The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example :
//save by First.java
package learnjava;
public class First{
public void msg() {
System.out.println("Hello");
}
}

//save by Second.java
package Java;
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
}
}

Output:

Hello

Points to remember
 When a package name is not specified, the classes are defined into the default package (the
current working directory) and the package itself is given no name. That is why, you were
able to execute assignments earlier.
 While creating a package, care should be taken that the statement for creating package must
be written before any other import statements.

// not allowed
import package p1.*;
package p3;
Below code is correct, while the code mentioned above is incorrect.
//correct syntax
package p3;
import package p1.*;

Creating Packages
To make a class as part of a package, you have to include the package statement as the first
statement in the source file.
Example 1
We shall write a class called Circle in package com.yyy. It is a good practice to store the source
codes and the classes in separate directories, to facilitate the distribution of classes without the
source codes. Suppose that we save the source as d:\myJavaProject\src\com\yyy\Circle.java,
and the compiled class as d:\myJavaProject\classes\com\yyy\Circle.class. Let's write the
source as follows:
// d:\myJavaProject\src\com\yyy\Circle.java
package com.yyy;
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
To compile the source using JDK, we need to use the -d option to specify the package base directory
of the compiled class d:\myJavaProject\classes as follows (-d defaulted to the current directory):
> javac -d d:\myJavaProject\classes d:\myJavaProject\src\com\yyy\Circle.java

The compiled class will be kept in d:\myJavaProject\classes\com\yyy\Circle.class. Directory


"com.yyy" will be created automatically. Instead of absolute path, we could also use relative path.
Let's write a test program to use this Circle class. Suppose that TestCircle.java is saved
in d:\myOtherProject.
// d:\myOtherProject\TestCircle.java
import com.yyy.Circle;
public class TestCircle {
public static void main(String[] args) {
Circle c = new Circle(1.23);
System.out.println(c.getRadius());
}
}
If we compile TestCircle.java from the directory d:\myOtherProject, we will get a error
message, as the compiler cannot find the com.yyy.Circle class.

d:> cd \myOtherProject

d:\myOtherProject> javac TestCircle.java


TestCircle.java:1: package com.yyy does not exist
import com.yyy.Circle;
^
We need to use the -cp (or -classpath) option to specify the base directory of the package com.yyy,
in order to locate com.yyy.Circle.
d:\myOtherProject> javac -cp d:\myJavaProject\classes TestCircle.java
To run the TestCircle, we again get a error, as JRE cannot find the com.yyy.Circle.
d:\myOtherProject> java TestCircle
Exception in thread "main" java.lang.NoClassDefFoundError: com/yyy/Circle
Let include the base directory of the package com.yyy in the classpath (to locate com.yyy.Circle):
d:\myOtherProject> java -cp d:\myJavaProject\classes TestCircle
Exception in thread "main" java.lang.NoClassDefFoundError: TestCircle
But now, the JRE can't even find the TestCircle class, which is located in the current directory. This
is because if CLASSPATH is not explicitly set, it defaulted to the current directory. However,
if CLASSPATH is explicitly set, it does not include the current directory unless the current directory is
included. Hence, we need to include current directory (denoted as '.') in the CLASSPATH, together
with the base directory of package com.yyy, separated by ';', as follows:
d:\myOtherProject> java -cp .;d:\myJavaProject\classes TestCircle
1.23
Example 2
Suppose that the TestCircle class in Example 1 in defined in a package com.abc, and save
as d:\myOtherProject\src\com\abc\TestCircle.java.
// d:\myOtherProject\src\com.abc\TestCircle.java
package com.abc;
import com.yyy.Circle;
public class TestCircle {
......
}
Suppose the compiled class is to be kept
as d:\myOtherProject\classes\com\abc\TestCircle.class.
-- To compile TestCircle.java, set the current directory and use relative paths for
TestCircle.
d:> cd \myOtherProject
d:\myOtherProject> javac -d classes -cp d:\myJavaProject\classes
src\com\abc\TestCircle.java
-- To run TestCircle, need to include the base directory of TestCircle and Circle in
classpath.
-- Also need to use the fully-qualified name (package name plus class name) for
TestCircle
d:\myOtherProject> java -cp classes;d:\myJavaProject\classes com.abc.TestCircle
Another Example
In this example, we have more than one classes in the package and the classes reference each others.
For example, the package com.zzz.project1.subproject2 has two classes: MyClass3 and MyClass4,
defined as follows:
package com.zzz.project1.subproject2;
public class MyClass3 {
private MyClass4 myClass4;
public MyClass3 () { // constructor
System.out.println("MyClass3 constructed");
myClass4 = new MyClass4(); // use MyClass4 in the same package
}
// main() included here for testing
public static void main(String[] args) {
new MyClass3();
}
}
package com.zzz.project1.subproject2;
public class MyClass4 { // constructor
public MyClass4() {
System.out.println("MyClass4 constructed");
}
}
Case 1: Source and class files in the same directory
Suppose that we keep the source and class files in the same directory,
says, $BASE_DIR\com\zzz\project1\subproject2. Note that you have to adhere to the sub-
directory structure specified in the package name for keeping the classes. I assume that
the CLASSPATH includes the current working directory.

To compile all the source files:


> cd $BASE_DIR
> javac com\zzz\project1\subproject2\*.java
The resultant class files will be placed in the same directory as the source files.
To execute the MyClass3, you need to issue the fully-qualified class name:
> cd $BASE_DIR
> java com.zzz.project1.subproject2.MyClass3

NOTES:
 To compile the program, you specify the directory path using directory separator '\'.
 To execute the class, you specify the fully-qualified class name using the dot '.'.
Alternatively, you can launch the class from any directory, provided that the $BASE_DIR is included in
the CLASSPATH environment variable. You can also use command-line option -classpath or -cp to
specify CLASSPATH used for this command:
> java –cp $BASE_DIR com.zzz.project1.subproject2.MyClass3

Case 2: Source and class files in separate directories

Suppose that you decided to keep the source files and classes in separate directories (for distribution
of classes without the sources), and the directory structure of your source files and classes is as
follows:

To compile the source files and place the classes in the desired directory, you can use the " -d" (for
destination) command-line option of the Java compiler, which specifies the location of the compiled
classes. You also need to specify the CLASSPATH of the classes, as MyClass3 uses MyClass4, as
follows:
> cd $SRC_BASE_DIR\zzz\project1\subproject2
> javac –d $CLASS_BASE_DIR -classpath .;$CLASS_BASE_DIR *.java
// try omitting the classpath and compile just MyClass3 which uses MyClass4
> javac –d $CLASS_BASE_DIR MyClass3.java
The sub-directory structure corresponding to the package name for the classes will be created
automatically if it does not already exist. In summary, during the compilation, you need to set both -
d (for destination of the classes), and -classpath (if one class references other classes in the
package).
In the above example, the source directory $SRC_BASE_DIR is "c:\javaproject\src" and the classes'
base directory $CLASS_BASE_DIR is "c:\javaproject\classes"
To execute the MyClass3:
> cd $CLASS_BASE_DIR
> java com.zzz.project1.subproject2.MyClass3

Using IDE
Managing packages and CLASSPATH yourself with obly JDK is troublesome. IDE such as Eclipses and
NetBeans could manage the packages and CLASSPATH for you!!
The Default Package
Every Java class must belong to a package. You can explicitly name the package by providing
a package statement in the beginning of the source file. If the package statement is omitted, the
class belongs to the so-called default package, with no sub-directory structure. Use of default
package is not recommended other than writing toy program and for quick testing.
CLASSPATH - For Locating Classes
CLASSPATH is an environment variable (i.e., global variables of the operating system available to all
the processes) needed for the Java compiler and runtime to locate the Java packages used in a Java
program. (Why not call PACKAGEPATH?) This is similar to another environment variable PATH, which is
used by the CMD shell to find the executable programs.
CLASSPATH can be set in one of the following ways:
1. CLASSPATH can be set permanently in the environment: In Windows, choose control panel ⇒
System ⇒ Advanced ⇒ Environment Variables ⇒ choose "System Variables" (for all the users)
or "User Variables" (only the currently login user) ⇒ choose "Edit" (if CLASSPATH already exists)
or "New" ⇒ Enter "CLASSPATH" as the variable name ⇒ Enter the required directories and JAR
files (separated by semicolons) as the value (e.g.,
".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need
to include the current working directory (denoted by '.') in the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:
> SET CLASSPATH

2. CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:
3. > SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

4. Instead of using the CLASSPATH environment variable, you can also use the command-line
option -classpath or -cp of the javac and java commands, for example,
5. > java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the
program. When an exception occurs program execution gets terminated. In such
cases we get a system generated error message. The good thing about
exceptions is that they can be handled in Java. By handling the exceptions we
can provide a meaningful message to the user about the issue rather than a
system generated message, which may not be understandable to a user.

Why an exception occurs?


There can be several reasons that can cause a program to throw exception. For
example: Opening a non-existing file in your program, Network connection
problem, bad input data provided by user etc.

Exception Handling
If an exception occurs, which has not been handled by programmer then
program execution gets terminated and a system generated error message is
shown to the user. For example look at the system generated exception below:
An exception generated by the system is given below

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


ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number
This message is not user friendly so a user will not be able to understand what
went wrong. In order to let them know the reason in simple language, we handle
exceptions. We handle such conditions and then prints a user friendly warning
message to user, which lets them correct the error as most of the time exception
occurs due to bad data provided by user.
Advantage of exception handling
Exception handling ensures that the flow of the program doesn’t break when an
exception occurs. For example, if a program has bunch of statements and an
exception occurs mid way after executing certain statements then the statements
after the exception will not execute and the program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of
program doesn’t break.

Difference between error and exception


Errors indicate that something severe enough has gone wrong, the application
should crash rather than try to handle the error.

Exceptions are events that occurs in the code. A programmer can handle such
conditions and take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when
you try to divide a number by zero this exception occurs because dividing a
number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an
array out of its bounds, for example array size is 5 (which means it has five
elements) and you are trying to access the 10th element.
Errors Exceptions

Errors in java are of type java.lang.Error. Exceptions in java are of type java.lang.Exception.

Exceptions include both checked as well as unchecked

All errors in java are unchecked type. type.

Checked exceptions are known to compiler where as

Errors happen at run time. They will not be known to unchecked exceptions are not known to compiler

compiler. because they occur at run time.

You can recover from exceptions by handling them

It is impossible to recover from errors. through try-catch blocks.

Errors are mostly caused by the environment in which

application is running. Exceptions are mainly caused by the application itself.

Examples :

Checked Exceptions : SQLException, IOException

Examples : Unchecked Exceptions :

java.lang.StackOverflowError, ArrayIndexOutOfBoundException, ClassCastException,

java.lang.OutOfMemoryError NullPointerException
Types of exceptions
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions

I have covered this in detail in a separate tutorial: Checked and Unchecked


exceptions in Java.

Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions
as the compiler checks them during compilation to see whether the programmer
has handled them or not. If these exceptions are not handled/declared in the
program, you will get compilation error. For example, SQLException,
IOException, ClassNotFoundException etc.

Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These
exceptions are not checked at compile-time so compiler does not check whether
the programmer has handled them or not but it’s the responsibility of the
programmer to handle these exceptions and provide a safe exit. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc.

Compiler will never force you to catch such exception or force you to declare it in
the method using throws keyword.

What topics are covered in the next tutorials


1. Try-catch in Java
2. Nested Try Catch
3. Checked and unchecked exceptions
4. Finally block in Java
5. try-catch-finally
6. finally block & return statement
7. Throw exception in Java
8. Example of throw keyword
9. Example of throws clause
10. Throws in Java
11. throw vs throws
12. Exception handling examples

Try block
The try block contains set of statements where an exception can occur. A try
block is always followed by a catch block, which handles the exception that
occurs in associated try block. A try block must be followed by catch blocks or
finally block or both.

Syntax of try block


try{
//statements that may cause an exception
}
While writing a program, if you think that certain statements in a program can
throw a exception, enclosed them in try block and handle that exception

Catch block
A catch block is where you handle the exceptions, this block must follow the try
block. A single try block can have several catch blocks associated with it. You
can catch different exceptions in different catch blocks. When an exception
occurs in try block, the corresponding catch block that handles that particular
exception executes. For example if an arithmetic exception occurs in try block
then the statements enclosed in catch block for arithmetic exception executes.

Syntax of try catch in java


try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Example: try catch block
If an exception occurs in try block then the control of execution is passed to the
corresponding catch block. A single try block can have multiple catch blocks
associated with it, you should place the catch blocks in such a way that the
generic exception handler catch block is at the last(see in the example below).
The generic exception handler can handle all the exceptions but you should
place is at the end, if you place it at the before all the catch blocks then it will
display the generic message. You always want to give the user a meaningful
message for each type of exception rather then a generic message.

class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:

You should not divide a number by zero


I'm out of try-catch block in Java.

Multiple catch blocks in Java


The example we seen above is having multiple catch blocks, lets see few rules
about multiple catch blocks with the help of examples. To read this in detail,
see catching multiple exceptions in java.
1. As I mentioned above, a single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions. Whether it is
ArrayIndexOutOfBoundsException or ArithmeticException or
NullPointerException or any other type of exception, this handles all of them. To
see the examples of NullPointerException and
ArrayIndexOutOfBoundsException, refer this article: Exception Handling example
programs.

catch(Exception e){
//This catch block catches all the exceptions
}
If you are wondering why we need other catch handlers when we have a generic
that can handle all. This is because in generic exception handler you can display
a message but you are not sure for which type of exception it may trigger so it
will display the same message for all the exceptions and user may not be able to
understand which exception occurred. Thats the reason you should place is at
the end of all the specific exception catch blocks

3. If no exception occurs in try block then the catch blocks are completely
ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can hanlde
ArithmeticException
catch(NullPointerException e) is a catch block that can handle
NullPointerException
5. You can also throw exception, which is an advanced topic and I have covered
it in separate tutorials: user defined exception, throws keyword, throw vs throws.

Example of Multiple catch blocks


class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:

Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks
executes sequentially when an exception occurs in try block. Which means if you
put the last catch block ( catch(Exception e)) at the first place, just after try block
then in case of any exception this block will execute as it can handle
all exceptions. This catch block should be placed at the last to avoid such
situations.

Finally block
I have covered this in a separate tutorial here: java finally block. For now you just
need to know that this block executes whether an exception occurs or not. You
should place those statements in finally blocks, that must execute whether
exception occurs or not.

Nested try catch block in Java – Exception


handling
BY CHAITANYA SINGH | FILED UNDER: EXCEPTION HANDLING

When a try catch block is present in another try block then it is called the nested
try catch block. Each time a try block does not have a catch handler for a
particular exception, then the catch blocks of parent try block are inspected for
that exception, if match is found that that catch block executes.

If neither catch block nor parent catch block handles exception then the system
generated message would be shown for the exception, similar to what we see
when we don’t handle exception.

Lets see the syntax first then we will discuss this with an example.
Syntax of Nested try Catch
....
//Main try block
try {
statement 1;
statement 2;
//try-catch block inside another try block
try {
statement 3;
statement 4;
//try-catch block inside nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}

}
//Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
....
Nested Try Catch Example
Here we have deep (two level) nesting which means we have a try-catch block
inside a nested try block. To make you understand better I have given the names
to each try block in comments like try-block2, try-block3 etc.

This is how the structure is: try-block3 is inside try-block2 and try-block2 is inside
main try-block, you can say that the main try-block is a grand parent of the try-
block3. Refer the explanation which is given at the end of this code.

class NestingDemo{
public static void main(String args[]){
//main try-block
try{
//try-block2
try{
//try-block3
try{
int arr[]= {1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist. The
* code should throw an exception
*/
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
}
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
}
catch(Exception e5){
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
Output:

ArrayIndexOutOfBoundsException handled in main try-block


As you can see that the ArrayIndexOutOfBoundsException occurred in the grand child
try-block3. Since try-block3 is not handling this exception, the control then gets
transferred to the parent try-block2 and looked for the catch handlers in try-
block2. Since the try-block2 is also not handling that exception, the control gets
transferred to the main (grand parent) try-block where it found the appropriate
catch block for exception. This is how the the nesting structure works.

Example 2: Nested try block


class Nest{
public static void main(String args[]){
//Parent try block
try{
//Child try block1
try{
System.out.println("Inside block1");
int b =45/0;
System.out.println(b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
//Child try block2
try{
System.out.println("Inside block2");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception");
System.out.println("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Inside parent try catch block");
}
catch(Exception e5){
System.out.println("Exception");
System.out.println("Inside parent try catch block");
}
System.out.println("Next statement..");
}
}
Output:

Inside block1
Exception: e1
Inside block2
Arithmetic Exception
Inside parent try catch block
Next statement..
This is another example that shows how the nested try block works. You can see
that there are two try-catch block inside main try block’s body. I’ve marked them
as block 1 and block 2 in above example.
Block1: I have divided an integer by zero and it caused an ArithmeticException,
since the catch of block1 is handling ArithmeticException "Exception: e1" displayed.

Block2: In block2, ArithmeticException occurred but block 2 catch is only


handling ArrayIndexOutOfBoundsException so in this case control jump to the
Main try-catch(parent) body and checks for the ArithmeticException catch
handler in parent catch blocks. Since catch of parent try block is handling this
exception using generic Exception handler that handles all exceptions, the
message “Inside parent try catch block” displayed as output.
Parent try Catch block: No exception occurred here so the “Next statement..”
displayed.

The important point to note here is that whenever the child catch blocks are not
handling any exception, the jumps to the parent catch blocks, if the exception is
not handled there as well then the program will terminate abruptly showing
system generated message.

Checked and unchecked exceptions in java


with examples
BY CHAITANYA SINGH | FILED UNDER: EXCEPTION HANDLING

There are two types of exceptions: checked exception and unchecked exception.
In this guide, we will discuss them. The main difference between checked and
unchecked exception is that the checked exceptions are checked at compile-
time while unchecked exceptions are checked at runtime.

What are checked exceptions?


Checked exceptions are checked at compile-time. It means if a method is
throwing a checked exception then it should handle the exception using try-catch
block or it should declare the exception using throws keyword, otherwise the
program will give a compilation error.

Lets understand this with the help of an example:

Checked Exception Example


In this example we are reading the file myfile.txt and displaying its content on the
screen. In this program there are three places where a checked exception is
thrown as mentioned in the comments below. FileInputStream which is used for
specifying the file path and name, throws FileNotFoundException. The read() method
which reads the file content throws IOException and the close() method which
closes the file input stream also throws IOException.

import java.io.*;
class Example {
public static void main(String args[])
{
FileInputStream fis = null;
/*This constructor FileInputStream(File filename)
* throws FileNotFoundException which is a checked
* exception
*/
fis = new FileInputStream("B:/myfile.txt");
int k;

/* Method read() of FileInputStream class also throws


* a checked exception: IOException
*/
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}

/*The method close() closes the file input stream


* It throws IOException*/
fis.close();
}
}
Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:


Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
Why this compilation error? As I mentioned in the beginning that checked
exceptions gets checked during compile time. Since we didn’t handled/declared
the exceptions, our program gave the compilation error.
How to resolve the error? There are two ways to avoid this error. We will see
both the ways one by one.

Method 1: Declare the exception using throws keyword.


As we know that all three occurrences of checked exceptions are inside main()
method so one way to avoid the compilation error is: Declare the exception in the
method using throws keyword. You may be thinking that our code is throwing
FileNotFoundException and IOException both then why we are declaring the
IOException alone. The reason is that IOException is a parent class of
FileNotFoundException so it by default covers that. If you want you can declare
them like this public static void main(String args[]) throws IOException, FileNotFoundException.

import java.io.*;
class Example {
public static void main(String args[]) throws IOException
{
FileInputStream fis = null;
fis = new FileInputStream("B:/myfile.txt");
int k;

while(( k = fis.read() ) != -1)


{
System.out.print((char)k);
}
fis.close();
}
}
Output:
File content is displayed on the screen.

Method 2: Handle them using try-catch blocks.


The approach we have used above is not good at all. It is not the best exception
handling practice. You should give meaningful message for each exception type
so that it would be easy for someone to understand the error. The code should
be like this:

import java.io.*;
class Example {
public static void main(String args[])
{
FileInputStream fis = null;
try{
fis = new FileInputStream("B:/myfile.txt");
}catch(FileNotFoundException fnfe){
System.out.println("The specified file is not " +
"present at the given path");
}
int k;
try{
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
fis.close();
}catch(IOException ioe){
System.out.println("I/O error occurred: "+ioe);
}
}
}
This code will run fine and will display the file content.

Here are the few other Checked Exceptions –

 SQLException
 IOException
 ClassNotFoundException
 InvocationTargetException
What are Unchecked exceptions?
Unchecked exceptions are not checked at compile time. It means if your program
is throwing an unchecked exception and even if you didn’t handle/declare that
exception, the program won’t give a compilation error. Most of the times these
exception occurs due to the bad data provided by user during the user-program
interaction. It is up to the programmer to judge the conditions in advance, that
can cause such exceptions and handle them appropriately. All Unchecked
exceptions are direct sub classes of RuntimeException class.

Lets understand this with an example:

Unchecked Exception Example


class Example {
public static void main(String args[])
{
int num1=10;
int num2=0;
/*Since I'm dividing an integer with 0
* it should throw ArithmeticException
*/
int res=num1/num2;
System.out.println(res);
}
}
If you compile this code, it would compile successfully however when you will run
it, it would throw ArithmeticException. That clearly shows that unchecked exceptions
are not checked at compile-time, they occurs at runtime. Lets see another
example.

class Example {
public static void main(String args[])
{
int arr[] ={1,2,3,4,5};
/* My array has only 5 elements but we are trying to
* display the value of 8th element. It should throw
* ArrayIndexOutOfBoundsException
*/
System.out.println(arr[7]);
}
}
This code would also compile successfully since ArrayIndexOutOfBoundsException is
also an unchecked exception.
Note: It doesn’t mean that compiler is not checking these exceptions so we
shouldn’t handle them. In fact we should handle them more carefully. For e.g. In
the above example there should be a exception message to user that they are
trying to display a value which doesn’t exist in array so that user would be able to
correct the issue.

class Example {
public static void main(String args[]) {
try{
int arr[] ={1,2,3,4,5};
System.out.println(arr[7]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("The specified index does not exist " +
"in array. Please correct the error.");
}
}
}
Output:

The specified index does not exist in array. Please correct the error.
Here are the few unchecked exception classes:

 NullPointerException
 ArrayIndexOutOfBoundsException
 ArithmeticException
 IllegalArgumentException
 NumberFormatException

Example 1: How to throw your own exception


explicitly using throw keyword
This example shows how to throw a custom exception using throw. Refer this
guide to understand how to create your own exceptions.

class MyOwnException extends Exception {


public MyOwnException(String msg){
super(msg);
}
}

class EmployeeTest {
static void employeeAge(int age) throws MyOwnException{
if(age < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args) {
try {
employeeAge(-2);
}
catch (MyOwnException e) {
e.printStackTrace();
}
}
}
Output:

beginnersbook.com.MyOwnException: Age can't be less than zero


Note: Method call should be in try block as it is throwing an exception.

Example 1: Exception propagation using throws


keyword
As you can see that we have an exception occurred in method1 which has been
handled in the chain-calling method method3(). This example shows how
exception propagation works.

class Example1{
void method1() throws ArithmeticException{
throw new ArithmeticException("Calculation error");
}
void method2() throws ArithmeticException{
method1();
}
void method3(){
try{
method2();
}
catch(ArithmeticException e){
System.out.println("ArithmeticException handled");
}
}
public static void main(String args[]){
Example1 obj=new Example1();
obj.method3();
System.out.println("End Of Program");
}
}
Output:

ArithmeticException handled
End Of Program
Java finally block when return statement is
encountered
BY CHAITANYA SINGH | FILED UNDER: EXCEPTION HANDLING

In my last tutorial, we discussed about finally block, which is used with a try block
and always execute whether exception occurs or not. Here we will see few
examples to understand the behaviour of finally block when a return statement is
encountered in try block.

Lets see this code snippet, What do you think? Will finally would execute even if
there is a return statement in try block as well as in catch block?

try {
//try block
...
return success;
}
catch (Exception ex) {
//catch block
.....
return failure;
}
finally {
System.out.println("Inside finally");
}
The answer is yes. finally block will execute. The only case where it will not
execute is when it encounters System.exit().

Finally: Example with return statement


class FinallyDemo
{
public static int myMethod()
{
try {
//try block
return 0;
}
finally {
//finally
System.out.println("Inside Finally block");
}
}
public static void main(String args[])
{
System.out.println(FinallyDemo.myMethod());
}
}
Output:

Inside Finally block


0
Does finally block Override the values returned by
try-catch block?
Yes. Finally block overrides the value returned by try and catch blocks, lets take
an example to understand this:

public static int myTestingFuncn(){


try{
....
return 5;
}
finally {
....
return 19;
}
}
This program would return value 19 since the value returned by try has
been overridden by finally.

You might also like