Java Event Handling in GUI Applications
Java Event Handling in GUI Applications
This imports all classes from the This imports all classes from
[Link] package, such as: the [Link] package,
such as:
•Frame
•Button •ActionEvent
•Label •ActionListener
•TextField •MouseEvent
•Checkbox •MouseListener
•Panel •KeyEvent
•and other GUI components. •WindowEvent
•ItemEvent
•and more...
Delegation Event Model
Component Description
Event Class Represents the actual event (e.g.,
ActionEvent, MouseEvent)
Event The object/component that generates the
Source event (e.g., Button, TextField)
Event The object that receives and handles the
Listener event (e.g., class implementing
ActionListener)
[Link] Source
• An event source is the object (typically a GUI
component) that generates an event when a user
interacts with it.
• A source must register listeners in order for the listener
to receive notification about specific type of event.
• Examples:
•Button (Button) – when clicked
•TextField (TextField) – when text changes or key is typed
•ScrollBar (ScrollBar) – when it is moved
•Window (Frame, JFrame) – when it is opened, closed, minimized
Registering a Listener:
public void addTypeListener(TypeListener el)
•Type = event type (e.g., Key, Mouse)
•el = event listener object
Examples:
•addKeyListener() → registers key listener
•addMouseListener() → registers mouse listener
Removing Listener:
public void removeTypeListener(TypeListener el)
[Link] Listener
• Important Notes
• Not all key presses produce characters
• Example: Shift, Ctrl, Alt do not generate KEY_TYPED.
• Example: Pressing Shift alone → KEY_PRESSED and KEY_RELEASED
happen, but no KEY_TYPED.
• Key Codes
•Each key has a constant value in KeyEvent called a Virtual Key Code
(VK codes).
•Examples:
•VK_A → Key 'A'
•VK_0 → Key '0'
•VK_ENTER → Enter key
•VK_LEFT, VK_RIGHT → Arrow keys
•VK_SHIFT, VK_CONTROL, VK_ALT → Modifier keys.
• VK Constants
•VK_0 to VK_9 → Number keys (0–9).
•VK_A to VK_Z → Alphabet keys (A–Z).
•Special keys: VK_ENTER, VK_ESCAPE, VK_PAGE_UP, etc.
•Independent of modifiers like Ctrl, Shift, or Alt.
•Getting Key Names
•[Link](int keyCode) → Returns the readable
name of a key code.
Example: [Link](KeyEvent.VK_A) → "A".
•Usage
•Typically used with KeyListener or KeyAdapter interfaces
to handle keyboard input in GUI programs
import [Link].*; public void keyPressed(KeyEvent e) {
import [Link].*; [Link]("Key Pressed: " +
[Link]([Link]()));
}
public class SimpleKeyEvent extends Frame
implements KeyListener {
public void keyReleased(KeyEvent e) {
Label label; [Link]("Key Released: " +
[Link]([Link]()));
}
public SimpleKeyEvent() {
label = new Label("Press any key...");
public void keyTyped(KeyEvent e) {
[Link](new Font("Arial", [Link],
18)); [Link]("Key Typed: " + [Link]());
add(label); }
4. Window ([Link])
•Subclass of Container.
•A top-level window → not contained in another object, sits directly
on the desktop.
•Usually not created directly.
•Instead, you use subclasses like Frame or Dialog.
5. Frame ([Link])
•Subclass of Window.
•Represents a standard application window with:
•Title bar
•Menu bar
•Borders
•Resizing corners
•If created from an applet, the Frame shows a warning message
(“Java Applet Window”) to alert users.
•If created from a standalone application, it shows a normal
window.
6. Canvas ([Link])
• Not part of the Panel/Frame hierarchy but important.
• Provides a blank window area on which you can draw shapes,
images, or graphics.
• Commonly used for custom graphics or game development in
AWT.
Layout Manager
• A layout manager automatically arranges components inside a container (like
a window or panel).
• It uses an algorithm to decide positions and sizes.
• Every Container (like JFrame, JPanel) has a layout manager.
• Set with:
void setLayout(LayoutManager layoutObj)
o If not set → default layout manager is used.
o If null is passed → Layout Manager is disabled → must manually set
positions using setBounds()
Responsibilities of Layout Manager
• Keeps track of all components added to a container.
• Decides placement & size when container is resized or displayed.
• Uses:
• minimumLayoutSize()
• preferredLayoutSize()
• Each component provides:
• getPreferredSize()
• getMinimumSize()
Customization:
•You can override size methods if creating custom components.
•Default values exist otherwise.
add(new Button("One"));
[Link]
• A layout manager with five regions:
• NORTH (top)
• SOUTH (bottom)
• EAST (right)
• WEST (left)
• CENTER (middle → expands to fill space).
Constructors
• BorderLayout()
• BorderLayout(int horz, int vert)
First form: Default layout, no extra spacing.
Second form: Lets you specify horizontal and vertical gaps between components
Constants (Regions)
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
Adding Components
void add(Component comp, Object region)
• comp → the component to add.
• region → one of the constants (NORTH, SOUTH, EAST,
WEST, CENTER).
Rules
•Only one component per region.
•If multiple are added to the same region, the last one replaces
the earlier.
•CENTER grows to occupy all remaining space.
import [Link]; add(new Label("The footer message might
go here."), [Link]);
import [Link].*;
add(new Button("Right"),
[Link]);
/*
add(new Button("Left"),
<applet code="BorderLayoutDemo" width=400 [Link]);
height=200>
</applet>
// Center text area with a quote
*/
String msg = "The reasonable man adapts
himself to the world"
public class BorderLayoutDemo extends Applet add(new TextArea(msg), [Link]);
{
}
public void init() {
}
// Use BorderLayout with default gaps
setLayout(new BorderLayout());
Label Constructors
[Link]()
•Creates a blank label.
[Link](String str)
•Creates a label containing the string str.
•Default alignment: left-justified.
Button Constructors
1. Button() – creates an empty button.
2. Button(String str) – creates a button with label str.
Button Methods
[Link] or get the label
•void setLabel(String str) → sets a new label.
•String getLabel() → returns the current label.
[Link] or get the action command
•void setActionCommand(String str) → sets a custom action
command (does not change the label).
•By default, the action command is the button’s label.
Handling Button Clicks
• Each click generates an ActionEvent.
• Components that handle this implement ActionListener.
• The actionPerformed(ActionEvent ae) method is called when the
button is pressed.
• Use [Link]() or [Link]() to determine which
button was clicked:
• By label: [Link]() (default is the button’s label).
• By object reference: [Link]() == buttonObject.
// Demonstrate Buttons
import [Link].*; add(yes); add(no); add(maybe);
import [Link].*;
import [Link].*; [Link](this);
[Link](this);
/* [Link](this);
<applet code="ButtonDemo" width=250 height=150> }
</applet>
*/ public void actionPerformed(ActionEvent ae) {
public class ButtonDemo extends Applet implements msg = "You pressed " + [Link]();
ActionListener {
repaint();
String msg = ""; }
Button yes, no, maybe;
Constructor Description
Creates a checkbox with no label. The initial state is
Checkbox()
unchecked.
Checkbox(String str) Creates a checkbox with label str. The initial state is unchecked.
boolean isEditable() Returns true if the text field is editable, otherwise false.
void setEditable(boolean canEdit) Makes the text field editable (true) or read-only (false).
void setEchoChar(char ch) Sets a character (like * or ?) to mask input (useful for passwords).
// Create TextFields
// Draw output on Applet
name = new TextField(15);
public void paint(Graphics g) {
pass = new TextField(10);
[Link](msg, 20, 100);
[Link]('*'); // Hide password characters
}
TextArea
• A multiline text input component in AWT, used when a single-line
TextField is insufficient, ideal for forms, editors, or logs. Subclass of
TextComponent.
Constructor Description
Creates an empty TextArea with default size and scrollbars
TextArea()
(SCROLLBARS_BOTH).
TextArea(String str) Creates a TextArea with initial text str and default size/scrollbars.
Constructor Description
void add(String name, int index) Adds name at the specified index (0-based); use -1 to add to the end.
Other Methods
int getItemCount() Returns the total number of items in the list.
void select(int index) Sets the item at the specified index (0-based) as the selected item.
String getItem(int index) Returns the name of the item at the specified index.
Event Types:
• Double-click (ActionEvent): Triggered when a list item is double-clicked. The
getActionCommand() method of the ActionEvent object returns the name of the
selected item.
• Single-click (ItemEvent): Triggered when an item is selected or deselected. The
getStateChange() method indicates if it’s a SELECTED or DESELECTED event, and
getItemSelectable() returns the List object that triggered the event.
Interfaces:
• Implement ActionListener for double-click events.
• Implement ItemListener for single-click selection/deselection events.
// Demonstrate Lists. // add lists to window
import [Link].*; add(os);
import [Link].*; add(browser);
import [Link].*; // register to receive action events
/* [Link](this);
<applet code="ListDemo" width=300 height=180> [Link](this);
</applet> }
*/ public void actionPerformed(ActionEvent ae) {
public class ListDemo extends Applet implements ActionListener { repaint();
List os, browser; }
String msg = ""; // Display current selections.
public void init() { public void paint(Graphics g) {
os = new List(4, true); int idx[];
browser = new List(4, false); msg = "Current OS: ";
// add items to os list idx = [Link]();
[Link]("Windows XP"); for(int i=0; i<[Link]; i++)
[Link]("Windows Vista"); msg += [Link](idx[i]) + " ";
[Link]("Solaris"); [Link](msg, 6, 120);
[Link]("Mac OS"); msg = "Current Browser: ";
// add items to browser list msg += [Link]();
[Link]("Internet Explorer"); [Link](msg, 6, 140);
[Link]("Firefox"); }
[Link]("Opera"); }
[Link](1);
Choice
• The Choice class in Java’s AWT creates a dropdown menu (pop-up list)
where users can select one item from a list of options. It’s a compact
menu that shows only the selected item when inactive and expands to
display all options when clicked. Below is a complete summary of the
text’s content:
• Purpose and Appearance:
• Used to create a pop-up list for user selection, functioning as a type of menu.
• When inactive, it displays only the currently selected item to save space.
• When clicked, the full list of choices appears, allowing the user to pick a new
item.
• Each item in the list is a string, shown as a left-justified label in the order added.
Constructors for [Link] Class
• Choice() Creates a new, empty Choice menu (pop-up list). This is the default constructor,
initializing an empty dropdown with no items. By default, the first added item will be
selected.
Methods for [Link] Class (Key Methods from Text)
• void add(String name) Adds a string item to the end of the Choice list. Items are appended
in the order of calls to this method, appearing as left-justified labels.
• String getSelectedItem() Returns the name of the currently selected item in the Choice
menu as a string.
• int getSelectedIndex() Returns the zero-based index of the currently selected item (0 for
the first item).
• int getItemCount() Returns the total number of items in the Choice list.
• void select(int index) Sets the selected item to the one at the specified zero-based index.
• void select(String name) Sets the selected item to the one matching the specified string
name in the list.
• String getItem(int index) Returns the name of the item at the specified zero-based index
in the list.
import [Link].*;
import [Link].*; // Add Choice menus to applet
import [Link].*; add(color);
add(shape);
/*
<applet code="SimpleChoiceDemo" width=250 height=150> // Register ItemListener for both menus
</applet> [Link](this);
*/ [Link](this);
public class SimpleChoiceDemo extends Applet implements ItemListener { }
Choice color, shape; // Two Choice menus
String msg = ""; // Message to display selections // Handle item selection events
public void init() { public void itemStateChanged(ItemEvent ie) {
// Create Choice menus repaint(); // Redraw applet when selection changes
color = new Choice(); }
shape = new Choice(); // Display current selections
public void paint(Graphics g) {
// Add items to color list msg = "Color: " + [Link]();
[Link]("Red"); [Link](msg, 10, 100);
[Link]("Blue"); msg = "Shape: " + [Link]();
[Link](msg, 10, 120);
// Add items to shape list }
[Link]("Circle"); }
[Link]("Square");
Sliders in Java GUI
• Sliders allow users to select a value from a defined range by dragging a knob or
thumb along a track. They are ideal for inputting numerical values within a
specific range, such as adjusting settings like volume, brightness, or progress.
• Purpose of Sliders
• Enable intuitive selection of a value from a continuous or discrete range (e.g., 0 to 100).
• Provide visual feedback as the user moves the knob.
• Support fine-tuned control for settings or parameters.
• Typical Use Cases
• Adjusting settings (e.g., volume, font size, color intensity).
• Selecting a value within a range (e.g., age, temperature).
• Controlling progress or position (e.g., in media players or scrollable content)
Menus in Java GUI
• Menus provide a structured way to organize and access commands or options
in a GUI application. They are typically displayed as dropdowns at the top of a
window (menu bar) or as context menus (right-click menus).
• Purpose of Menus
• Organize application commands (e.g., File, Edit, Help).
• Provide quick access to actions (e.g., Save, Copy, Exit).
• Support hierarchical navigation with submenus for grouped functionality.
• Typical Use Cases
• Application navigation (e.g., File > New, Open, Save).
• Context-sensitive actions (e.g., right-click to copy/paste).
• Organizing settings or tools in complex applications.
Dialog Boxes in Java
• A Dialog Box is a special type of window used to display messages or to
obtain user input.
• They are usually child windows of a top-level window (like a Frame).
• Dialog boxes don’t have menu bars, but they can contain other GUI
controls (labels, buttons, text fields, etc.).
• Types of Dialog Boxes
• Modal Dialog Box
• Blocks user interaction with other windows until it is closed.
• Example: Save File dialog.
• Modeless Dialog Box
• Does not block other windows; user can still interact with the rest of the program.
• Example: Find/Replace dialog in text editors.
• In AWT, dialog boxes are implemented using the Dialog class.
• Two commonly used constructors:
• Dialog(Frame parentWindow, boolean mode)
• Dialog(Frame parentWindow, String title, boolean mode)
parentWindow → the owner of the dialog box.
mode → if true, dialog is modal; if false, it is modeless.
title → optional string for dialog title.
import [Link]; [Link](new FlowLayout());
import [Link].*;
</applet>
[Link](new ActionListener() {
Dialog dialog; }
});
[Link](new FlowLayout()); }
});
[Link](openButton); [Link](true);
[Link](200, 100);
Exception
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
Exception Handling Fundamentals :
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Program statements that you want to monitor for exceptions are contained within a try block. If
an exception occurs within the try block, it is thrown.
Your code can catch this exception using catch and handle it in some rational manner. System-
generated exceptions are automatically thrown by the Java run-time system
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
Java Exception Keywords:
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
The "try" keyword is used to specify a block where we should
try place an exception code. It means we can't use try block alone.
The try block must be followed by either catch or finally.
The "catch" block is used to handle the exception. It must be
catch preceded by try block which means we can't use catch block
alone. It can be followed by finally block later.
The "finally" block is used to execute the necessary code of the
finally
program. It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
The "throws" keyword is used to declare exceptions. It specifies
throws that there may occur an exception in the method. It doesn't
throw an exception. It is always used with method signature.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered
as unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between checked and unchecked exceptions :
1) Checked Exception: The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions [Link], SQLException etc. Checked exceptions
are checked at compile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.
Uncaught Exceptions in Java :
In java, assume that, if we do not handle the exceptions in a program. In this case, when an
exception occurs in a particular function, then Java prints a exception message with the help of
uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us to
handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method known
dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions.
Example:
import [Link];
public class UncaughtExceptionExample
{
public static void main(String[] args)
{
Scanner read = new Scanner([Link]);
[Link]("Enter the a and b values: ");
int a = [Link]();
int b = [Link]();
int c = a / b;
[Link](a + "/" + b +" = " + c);
}
}
In the above example code, we are not used try and catch blocks, but when the value of b is
zero the division by zero exception occurs and it caught by the default exception handler.
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
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.
Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter.
The catch block must be used after the try block only. You can use multiple catch block with a
single try block.
Internal Working of Java try-catch block
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:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed
Using try and catch:
This is the general form of an exception-handling block:
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 after try block ends
}
Here, ExceptionType is the type of exception that has occurred.
When an exception is thrown, it is caught by the corresponding catch statement which then
processes the exception.
When no exception is thrown, try block ends normally and catch statements are bypassed.
Thus catch statements are executed only if an exception is thrown.
Types of Exceptions:
Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler.
Unchecked Exceptions: The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile time. In simple words, if a
program throws an unchecked exception, and even if we didn’t handle or declare it, the
program would not give a compilation error.
User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
List of common checked exceptions in Java:
Exception class Description
OutOfMemoryError This error is raised when the JVM runs out of memory.
VirtualMachineError This is the superclass of all errors that occur in the JVM.
Syntax:
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
} catch (ArithmeticException e)
{ // catch divide-by-zero error
[Link]("Division by zero.");
}
[Link]("After catch statement.");
}
}
output:
Division by zero.
After catch statement.
Notice that the call to println( ) inside the try block is never executed. Once an exception is
thrown, program control transfers out of the try block into the catch block.
Put differently, catch is not “called,” so execution never “returns” to the try block from a
catch. Thus, the line “This will not be printed.” is not displayed.
Once the catch statement has executed, program control continues with the next line in the
program following the entire try/catch mechanism.
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0;
}
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}
}
Output:
[Link]: / by zero
rest of the code
public class TryCatchExample5
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
catch(Exception e)
{
// displaying the custom message
[Link]("Can't divided by zero");
}
}
}
Output:
Can't divided by zero
Solution by exception handling
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}
}
Ourput:
[Link]: / by zero
rest of the code
Multiple Catch Blocks in Java
Multiple catch blocks in Java are used to catch/handle multiple exceptions that may be thrown
from a particular code section. A try block can have multiple catch blocks to handle multiple
exceptions.
try {
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is thrown to
the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Handling Multiple Exceptions Within A Single Catch Block:
public class ExcepTest {
When any try block does not have a catch block for a particular exception, then the catch block
of the outer (parent) try block are checked for that exception, and if it matches, the catch block
of outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then the Java
runtime system will handle the exception. Then it displays the system generated message for
that exception.
Java throw, throws and finally Keyword:
Throw, throws and finally are the keywords in Java that are used in exception handling.
Throws is used to declare the list of possible exceptions with the method signature.
Whereas finally block is used to execute essential code, specially to release the occupied
resources.
Java Throw
The throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can
be thrown. Program execution stops on encountering throw statement, and the closest catch statement is
checked for matching type of exception.
Syntax :
throw new ExceptionType("Error message");
throw keyword is used to throw an exception throws keyword is used to declare an exception
explicitly. possible during its execution.
throw keyword is followed by an instance of throws keyword is followed by one or more Exception
Throwable class or one of its sub-classes. class names separated by commas.
We cannot throw multiple exceptions using throw We can declare multiple exceptions (separated by
keyword. commas) using throws keyword.
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code is always
executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type
statements that you want to execute, no matter what happens in the protected code. A finally block appears at
the end of catch block.
Example finally Block
In this example, we are using finally block along with try block. This program throws an exception and due to
exception, program terminates its execution but see code written inside the finally block executed. It is because
of nature of finally block that guarantees to execute the code.
public class FinallyExample {
public static void main(String args[]){
try {
[Link]("Inside try block");
// below code throws divide by zero exception
int data=25/0;
[Link](data);
}
// handles the Arithmetic Exception / Divide by zero exception
catch (ArithmeticException e){
[Link]("Exception handled");
[Link](e);
}
// executes regardless of exception occurred or not
finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
// Java program to demonstrate working of try,
// catch and finally
class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
[Link]("result" + result);
}
catch (ArithmeticException e) {
[Link]("Exception caught:Division by zero");
}
finally {
Output
Exception caught:Division by zero
I am in final block
Why is finally block needed?
In Java, the finally block is used to place critical code such as cleanup code, closing a file, or closing a connection.
The finally block checks whether an exception has been raised and whether it has been handled. Regardless of
whether the exception happens, a fina block contains all the crucial statements.
class MyException extends Exception {
{ [Link](a+b);
private int ex; }
MyException(int a) }
{
ex = a; public static void main(String[] args)
} {
public String toString() try
{ {
return "MyException[" + ex +"] is less than zero"; sum(-10, 10);
} }
} catch(MyException me)
{
class test [Link](me); //it calls the toString() method
{ of user-defined Exception
static void sum(int a,int b) throws MyException }
{ }
if(a<0) }
{
throw new MyException(a); //calling constructor of
user-defined exception class
}
else
Output
MyException[-10] is less than zero
This example defines a subclass of Exception called MyException. This subclass is quite
simple: it has only a constructor plus an overloaded toString( ) method that displays the
value of the exception. The ExceptionDemo class defines a method named compute( ) that
throws a MyException object. The exception is thrown when compute( )’s integer parameter
is greater than 10. The main( ) method sets up an exception handler for MyException, then
calls compute( ) with a legal value (less than 10) and an illegal one to show both paths
through
the code. Here is the result:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
Java Custom Exception
The custom exception refers to the creation of your own exception to customize
an exception according to the needs. The custom exceptions are derived from
the Exception class.
Create a Custom Exception in Java:
Creating your own exception subclass in Java allows you to define custom exceptions that
serve to specific errors in your application. This approach helps in improving code readability
and managing exceptional conditions effectively.
Syntax:
class MyException extends Exception {
}
class InvalidAgeException extends Exception }
{ }
public InvalidAgeException(String message) public static void main(String[] args) {
{ UserRegistration registration = new UserRegistration();
super(message); try {
} [Link](“XYZ", 20); // Valid registration
} [Link](“ABC", 16); // Invalid age, will
throw exception
public class UserRegistration } catch (InvalidAgeException e)
{ {
public void registerUser(String name, int age) throws [Link]("Registration Error: " +
InvalidAgeException { [Link]());
if (age < 18) }
{ }
throw new InvalidAgeException("User " + name + " must }
be 18 years or older.");
}
else
{
[Link]("User " + name + " registered
successfully.");
InvalidAgeException extends the Exception class, making it a checked exception (since it
extends Exception).
InvalidAgeException(String message) is the constructor that initializes the exception message
using super(message)
class UserRegistration where we will validate the age of a user during registration and throw
InvalidAgeException if the age is less than 18.
InvalidAgeException Class Extends Exception, making it a checked [Link] Provides a
constructor that calls super(message) to initialize the exception message.
In UserRegistration Class registerUser(String name, int age): Validates the age provided during
user registration. If age < 18, it throws InvalidAgeException with a specific error message. In
main() method, demonstrates the usage of registerUser() method with both valid and invalid
age inputs, catching InvalidAgeException to handle the error scenario.
The advantages of Exception Handling in Java are as follows:
Provision to Complete Program Execution
Easy Identification of Program Code and Error-Handling Code
Propagation of Errors
Meaningful Error Reporting
Identifying Error Types
Java throw keyword
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message with
it that provides the error description. These exceptions may be related to user inputs, server,
etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception.
The syntax of the Java throw keyword is given below.
throw new exception_class("error message");
public class TestThrow1 {
//function to check if person is eligible to vote or not
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 {
[Link]("Person is eligible to vote!!");
}
}
public static void main(String args[]){
//calling the function
validate(13);
[Link]("rest of the code...");
}
}
Output:
Java Catch Multiple Exceptions Java
Multi-catch block 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.
public class MultipleCatchBlock1
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
} catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
} catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
} catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
public class MultipleCatchBlock2 [Link]("Parent Exception occurs");
{ }
public static void main(String[] args) [Link]("rest of the code");
{ }
try }
{
int a[]=new int[5];
[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception
occurs");
}
catch(Exception e)
{