You are on page 1of 8

Exception Handling

Exception Handling is the mechanism to handle runtime malfunctions. We need to handle such exceptions to prevent abrupt
termination of program. The term exception means exceptional condition, it is a problem that may arise during the
execution of program. A bunch of things can lead to exceptions, including programmer error, hardware failures, files that
need to be opened cannot be found, resource exhaustion etc.

Exception
A Java Exception is an object that describes the exception that occurs in a program. When an exceptional events occurs in
java, an exception is said to be thrown. The code that's responsible for doing something about the exception is called
an exception handler.

Exception class Hierarchy


All exception types are subclasses of class Throwable, which is at the top of exception class hierarchy.

Exception class is for exceptional conditions that program should catch. This class is extended to create user
specific exception classes.

RuntimeException is a subclass of Exception. Exceptions under this class are automatically defined for programs.

Exception are categorized into 3 category.

Checked Exception
The exception that can be predicted by the programmer.Example : File that need to be opened is not found. These type
of exceptions must be checked at compile time.

Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at compile
time. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked
exceptions are checked at runtime.

Error
Errors are typically ignored in code because you can rarely do anything about an error. Example : if stack overflow
occurs, an error will arise. This type of error is not possible handle in code.

Uncaught Exceptions
When we don't handle the exceptions, they lead to unexpected program termination. Lets take an example for better
understanding.
class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a;

// Divide by zero, will lead to exception

}
}
This will lead to an exception at runtime, hence the Java run-time system will construct an exception and then throw it. As
we don't have any mechanism for handling exception in the above program, hence the default handler will handle the
exception and will print the details of the exception on the terminal.

Exception handling
Exception handling is the process of responding to the occurrence, during computation, of exceptions anomalous or
exceptional conditions requiring special processing often changing the normal flow of program execution. It is provided
by specialized programming language constructs or computer hardware mechanisms.
In general, an exception is handled (resolved) by saving the current state of execution in a predefined place and switching
the execution to a specific subroutine known as anexception handler. If exceptions are continuable, the handler may later
resume the execution at the original location using the saved information. For example, a floating pointdivide by
zero exception will typically, by default, allow the program to be resumed, while an out of memory condition might not be
resolvable transparently.
Alternative approaches to exception handling in software are error checking, which maintains normal program flow with
later explicit checks for contingencies reported using special return values or some auxiliary global variable such as
C's errno or floating point status flags; or input validation to preemptively filter exceptional cases.
Some programmers write software with error reporting features that collect details that may be helpful in fixing the
problem, and display those details on the screen, or store them to a file such as a core dump, or in some cases an automatic
error reporting system such as Windows Error Reporting can automatically phone home and email those details to the
programmers.

An exception (or exceptional event) is a problem that arises during theexecution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore these
exceptions are to be handled.
An exception can occur for many different reasons, below given are some scenarios where
exception occurs.

A user has entered invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or the JVM has run
out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Based on these we have three categories of Exceptions you need to understand them to know
how exception handling works in Java,

Checked exceptions: A checked exception is an exception that occurs at the compile


time, these are also called as compile time exceptions. These exceptions cannot simply be
ignored at the time of compilation, the Programmer should take care of (handle) these
exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then anFileNotFoundException occurs, and
compiler prompts the programmer to handle the exception.

import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]){
File file=new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
If you try to compile the above program you will get exceptions as shown below.

C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or
declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
Note: Since the methods read() and close() of FileReader class throws IOException, you can
observe that compiler notifies to handle IOException, along with FileNotFoundException.

Unchecked exceptions: An Unchecked exception is an exception that occurs at the time


of execution, these are also called as Runtime Exceptions, these include programming

bugs, such as logic errors or improper use of an API. runtime exceptions are ignored at the
time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the
6th element of the array then anArrayIndexOutOfBoundsExceptionexception occurs.
public class Unchecked_Demo {
public static void main(String args[]){
int num[]={1,2,3,4};
System.out.println(num[5]);
}
}
If you compile and execute the above program you will get exception as shown below.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely
do anything about an error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.

Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the java programs. Errors are generated to indicate errors generated by the runtime
environment. Example : JVM is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.

Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub packages. Many
implementations of Java use a hierarchical file system to manage source and class files. It is easy to organize
class files into packages. All we need to do is put related class files in the same directory, give the directory a
name that relates to the purpose of the classes, and add a line to the top of each class file that declares the
package name, which is the same as the directory name where they reside.
In java there are already many predefined packages that we use while programming.
For example: java.lang, java.io, java.util etc.
However one of the most useful feature of java is that we can define our own packages
Advantages of using a package
Before discussing how to use them Let see why we should use packages.

Reusability: Reusability of code is one of the most important requirements in the software industry.
Reusability saves time, effort and also ensures consistency. A class once developed can be reused by any
number of programs wishing to incorporate the class in that particular program.

Easy to locate the files.

In real life situation there may arise scenarios where we need to define files of the same name. This
may lead to name-space collisions. Packages are a way of avoiding name-space collisions.

Types of package:
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in
packages.

LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is
implemented by all the classes of layout managers. There are following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout

6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region
(area) may contain one component only. It is the default layout of frame or window. The BorderLayout provides five
constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

BorderLayout(): creates a border layout but with no gaps between the components.

JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.

Example of BorderLayout class:

import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
JButton
JButton
JButton
JButton
JButton

b1=new
b2=new
b3=new
b4=new
b5=new

JButton("NORTH");;
JButton("SOUTH");;
JButton("EAST");;
JButton("WEST");;
JButton("CENTER");;

f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

You might also like