Prgms
Prgms
Try n catch
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
In Java, the finally keyword is used in exception handling to define a block of code that will
always execute after a try block, regardless of whether an exception was thrown or not. It’s
typically used for code that needs to be executed no matter what, such as closing files or
releasing resources.
Purpose of finally
Ensure Execution: The code inside the finally block is guaranteed to execute whether or not
an exception occurs in the try block.
Cleanup Resources: It's commonly used for resource cleanup, such as closing files, network
connections, or releasing database resources.
Basic Syntax
java
Copy code
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}
1. Program to handle Null Pointer Exception and use the “finally” method
to display a message to the user.
import java.io.*;
class prg12
{
public static void main(String[] args)
{
String ptr = null;
try
{
System.out.println("Inside try
block"); if ("gfg".equals(ptr))
System.out.println("Same");
else
System.out.println("Not Same");
}
catch(NullPointerException e)
{
System.out.println("Exception handled"); System.out.println(e);
}
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
OUTPUT:
((import java.awt.*; is used to include all the classes and interfaces from the
java.awt, which provides classes for creating and managing graphical user
interfaces (GUIs) in Java.))
((Swing is a Java toolkit for building graphical user interfaces (GUIs) for
applications and applets. ))
OUTPUT: