Handle Exception Without Catch Block Example in Java
Introduction
Handle Exception without Catch block is a classic Java console program that demonstrates the concept with complete source code and sample output. Exceptions represent runtime errors; Java uses try-catch-finally to handle them safely.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Syntax
static void <method_name>() throws <exception_name>{
try{
//Do something
}finally{
//Do something always even when there is an exception
}
}Handle Exception without Catch block Example Program
public class HandleExceptionWithoutCatchBlock {
static void doStringOperation() throws Exception{
try{
String text = null;
//Trying to replace character in null string. Exception is caused.
text = text.replaceAll("/", "-");
}finally{
//This code inside finally block will be executed always (Even if there is an exception)
System.out.println("Successfully completed string operation");
}
}
public static void main(String[] args) throws Exception{
doStringOperation();
}
}Sample Output
Successfully completed string operation
Exception in thread "main" java.lang.NullPointerException
at learnjavaprograms.HandleExceptionWithoutCatchBlock.doStringOperation(HandleExceptionWithoutCatchBlock.java:17)
at learnjavaprograms.HandleExceptionWithoutCatchBlock.main(HandleExceptionWithoutCatchBlock.java:25)
Java Result: 1When to use
Use this handle exception without catch block example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
String text = null;updates a variable used in the calculation or output. -
text = text.replaceAll("/", "-");updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
Compare your console output with the sample output for Handle Exception without Catch block to confirm the program behaves correctly.