Module 4
Module 4
Module IV
Exception Handling in
Java
• An exception is an unwanted or unexpected event,
which occurs during the execution of a program
i.e at run time, that disrupts the normal flow of
the program’s instructions.
2. Unchecked Exception
• The classes which inherit RuntimeException are
known as unchecked exceptions e.g.
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
• Unchecked exceptions are not checked at compile-
time, but they are checked at runtime.
• Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally.
• try
How
• Program statements that you think can raise
Programmer exceptions are contained within a try block.
handles an
exception? • catch
• If an exception occurs within the try block, it is
thrown. Your code can catch this exception (using
catch block) and handle it in some rational
manner.
• throw
• System-generated exceptions are automatically thrown
by the Java run-time system.
• To manually throw an exception, use the keyword
throw.
• throws
• Any exception that is thrown out of a method must be
specified as such by a throws clause.
• finally
• Any code that absolutely must be executed after a try
block completes is put in a finally block.
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
int[] arr = new int[4];
int i = arr[4];
Example // the following statement will never execute
System.out.println("Hi, I want to execute");
}
}
• Output
Hello World
Handling catch(Exception e)
{
System.out.println("Exception Handled");
}
System.out.println("Hi, I want to execute");
}
}
• Output
Hello World
Exception Handled
2. String s=null;
Common System.out.println(s.length());//NullPointerException
Scenarios
of Java 3. String s="abc";
Exceptions int i=Integer.parseInt(s);//NumberFormatException
public class TryCatchExample{
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exc
eption 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
• If an exception occurs at the particular statement
of try block, the rest of the block code will not
execute.
• So, it is recommended not to keeping the code in
try block that will not throw an exception.
Points to • In a method, there can be more than one
Remember statements that might throw exception, So put all
these statements within its own try block and
provide separate exception handler within
own catch block for each of them.
• A try block must be followed by catch blocks or
finally block or both.
• If no exception occurs in try block then the catch
blocks are completely ignored.
• we cannot write any statements in between
try, catch and finally blocks and
these blocks form one unit.
• Sometimes a situation may arise where a part of a
block may cause one error and the entire block
itself may cause another error.
Nested try • In such cases, exception handlers have to be
nested.
class Main{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException
e){System.out.println(e);}
System.out.println("other statement");
}catch(Exception
e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
• Output
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
other statement
normal flow..
• Java finally block is a block that is used to execute
important code such as closing connection, stream
etc.
Java finally • Java finally block is always executed whether
block exception is handled or not.
• Java finally block follows try or catch block.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
Example {System.out.println(e);}
Finally
{System.out.println("finally block is always executed");}
Example:Excep m();
}
tion
void p(){
Propagation
try{
n();
}catch(Exception e){System.out.println("exceptio
n handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExc
eptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
• Output:
exception handled
normal flow...
• The Java throw keyword is used to explicitly
throw an exception.
Example1 try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Main obj=new Main();
obj.p();
System.out.println("normal flow...");
}
}
• Output
• Main.java:4: error: unreported exception IOException; must be
caught or declared to be thrown
• throw new IOException("device error");//checked exception
• ^
• 1 error
import java.io.IOException;
class Main{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
Example2 try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Main obj=new Main();
obj.p();
System.out.println("normal flow...");
}
}
• Output
exception handled
normal flow...
• Rule: If you are calling a method that declares an
exception, you must either caught or declare the
exception.
• There are two cases:
• Case1:You caught the exception i.e. handle the exception
using try/catch.
• Case2:You declare the exception i.e. specifying throws
with the method.
• If you are creating your own Exception that is
known as custom exception or user-defined
Java exception.
• Java custom exceptions are used to customize the
Custom exception according to user need.
Exception • By the help of custom exception, you can have your
own exception and message.
class MyException extends Exception
{
public MyException(String s)
{
super(s);
}
}
public class Main
{
public static void main(String args[])
{
Example1
try
{
throw new MyException("Exception Message");
}
catch (MyException ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
• Output:
Caught
Exception Message
class MyException extends Exception
{
}
public class Main
{
public static void main(String args[])
{
Example2
try
{ throw new MyException();
}
catch (MyException ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
• Output
Caught
null
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException{
1.Throwable(Throwable cause) :-
• Where cause is the exception that causes the
current exception.
2.Throwable(String msg, Throwable cause) :-
• Where msg is the exception message and cause is
the exception that causes the current exception.
• Methods Of Throwable class Which
support chained exceptions in java :
1.getCause() method :-
• This method returns actual cause of an exception.
2.initCause(Throwable cause) method :-
• This method sets the cause for the calling
exception.
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
NumberFormatException ex =
new
NumberFormatException("Exception");
ex.initCause(new NullPointerException(
Example exception"));
"This is actual cause of the
throw ex;
}
catch(NumberFormatException ex)
{
System.out.println(ex);
System.out.println(ex.getCause());
}
}
}
• Output
java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is
actual cause of the exception
• In Java, the try-with-resources statement is a
try statement that declares one or more
resources.
• The resource is as an object that must be
The try-with- closed after finishing the program.
resources • The try-with-resources statement ensures that
each resource is closed at the end of the
statement statement execution.
• You can pass any object that implements
java.lang.AutoCloseable
• The following example writes a string into a
file.
• It uses an instance of FileOutputStream to
write data into the file.
• FileOutputStream is a resource that must be
closed after the program is finished with it.
• So, in this example, closing of resource is
done by itself try.
import java.io.FileOutputStream;
public class TryWithResources {
public static void main(String args[]){
// Using try-with-resources
try(FileOutputStream fileOutputStream =newFileOutputStream("/java7-
new-features/src/abc.txt"))
{
String msg = "Welcome to javaTpoint!";
byte byteArray[] = msg.getBytes(); //converting string into byte array
Example fileOutputStream.write(byteArray);
System.out.println("Message written to file successfuly!");
}
catch(Exception exception){
System.out.println(exception);
}
}
}
• Output:
• Message written to file successfuly!
• An assertion allows testing the correctness of any
assumptions that have been made in the program.
• Assertion is achieved using the assert statement in
Java.
• While executing assertion, it is believed to be true.
Java Assertion • If it fails, JVM throws an error
named AssertionError.
• It is mainly used for testing purposes during
development.
import java.util.Scanner;
class Test
{
public static void main( String args[]
)
{
Example int value = 15;
assert value >= 20 : "
Underweight";
System.out.println("value is
"+value);
}
}
• Output:
value is 15
Method Description
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default
false.
• To create simple awt example, you need a
frame.
Java • There are two ways to create a frame in AWT.
AWT Example • By extending Frame class (inheritance)
• By creating the object of Frame class (association)
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
AWT Example
setSize(300,300);//frame size 300 width and 300 height
by Inheritance
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
Output
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
AWT Example f.add(b);
by Association f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}
Output
• The object of Label class is a component for
placing text in a container.
Java AWT • It is used to display a single line of read only text.
Label • The text can be changed by an application but a
user cannot edit it directly.
import java.awt.*;
class First{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label.");
l1.setBounds(50,100, 100,30);
l2=new Label("Second Label.");
Example l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output
• The object of a TextField class is a text component
Java that allows the editing of a single line text.
AWT TextField • It inherits TextComponent class
import java.awt.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome.");
t1.setBounds(50,100, 200,30);
t2=new TextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output
• The object of a TextArea class is a multi line
region that displays text.
Java • It allows the editing of multiple line text.
AWT TextArea • It inherits TextComponent class.
import java.awt.*;
public class First
{
First(){
Frame f= new Frame();
TextArea area=new TextArea("Welcome to AWT
Tutorial");
area.setBounds(10,30, 300,300);
Example f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new First();
}
}
Output
• The Checkbox class is used to create a
checkbox.
Java AWT • It is used to turn an option on (true) or off
Checkbox (false).
• Clicking on a Checkbox changes its state from
"on" to "off" or from "off" to "on".
import java.awt.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100,150, 50,50);
Example f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
Output
• The object of Choice class is used to show popup
menu of choices.
Java AWT • Choice selected by user is shown on the top of a
menu.
Choice
• It inherits Component class.
import java.awt.*;
public class ChoiceExample
{
ChoiceExample(){
Frame f= new Frame();
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
• Background Events -
• Those events that do not require the interaction of end user
are known as background events.
• Operating system interrupts, hardware or software failure,
timer expires, an operation completion are the example of
background events.
• Event Handling is the mechanism that controls the
event and decides what should happen if an event
occurs.
• The Delegation Event Model has the following key
participants namely:
• Source -
Event • The source is an object on which event occurs.
• Source is responsible for providing information of the
Handling occurred event to it's handler.
• Java provide as with classes for source object.
• Listener -
• It is also known as event handler.
• Listener is responsible for generating response to an event.
• Once the event is received , the listener process the event an
then returns.
Event Classes
Description Listener Interface
ActionEvent generated when button is pressed, menu- ActionListener
item is selected, list-item is double clicked
Example l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
public void keyTyped(KeyEvent e) {
l.setText("Key Typed");
}
Example 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();
}
}
Output
• You can also add gap between components by
using the following line of code
• f.setLayout(new BorderLayout(10,10));
• Then the output will be as follows
• Java GridLayout
• The GridLayout is used to arrange the components
in rectangular grid.
• One component is displayed in each rectangle.
• Constructors of GridLayout class
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Output
• Java FlowLayout
• The FlowLayout is used to arrange the
components in a line, one after another (in a
flow).
• It is the default layout of applet or panel.
• Fields of FlowLayout class
• public static final int LEFT
• public static final int RIGHT
• public static final int CENTER
• public static final int LEADING
• public static final int TRAILING
• Constructors of FlowLayout class
Example
Button b4=new Button("4");
Button b5=new Button("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
Output
• The Panel is a simplest container class.
• It provides space in which an application can attach
any other component.
Java AWT Panel • It inherits the Container class.
• It doesn't have title bar.
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
Example panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output
Module IV-Syllabus
• Exception Handling & GUI Design
• When to use exception handling, Java exception hierarchy, finally block, Stack
unwinding, Chained exceptions, Declaring new exception types, Assertions,
try with resources. Simple I/O with GUI, Basic GUI Components, GUI
Event handling, Adapter classes, Layout managers