Java
Java
An exception (or exceptional event) is a problem that arises during the execution
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.
Page 1
Course II_BCA NEP Syllabus
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
Page 2
Course II_BCA NEP Syllabus
3) Error
try block
The try block contains a set of statements that might throw an exception
It must be used within the method.
A try block must be followed by catch blocks or finally block or both.
Page 3
Course II_BCA NEP Syllabus
Page 4
Course II_BCA NEP Syllabus
Example Program1
Example Program2
Page 5
Course II_BCA NEP Syllabus
Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain
a different exception handler.
Page 6
Course II_BCA NEP Syllabus
Java finally block is a block used to execute important code such as closing the
connection, etc.
throw
The throw keyword in Java is used to explicitly throw an exception from a method or
any block of code. We can throw either checked or unchecked exception. The throw
keyword is mainly used to throw custom exceptions.
Example Program
if(age<18)
Page 7
Course II_BCA NEP Syllabus
else
checkAge(13);
System.out.println("End Of Program");
throws
Example program1
int t = a/b;
return t;
Page 8
Course II_BCA NEP Syllabus
try{
System.out.println(division(15,0));
catch(ArithmeticException e){
Example program2
class ThrowsExecp
try
fun();
Page 9
Course II_BCA NEP Syllabus
catch(IllegalAccessException e)
System.out.println("caught in main.");
Custom Exception
String message;
CustomException(String str) {
message = str;
Page 10
Course II_BCA NEP Syllabus
try {
} catch(CustomException e) {
System.out.println(e);
Output
Page 11
Course II_BCA NEP Syllabus
System.out.println(e);
}
System.out.println("Continuing execution...");
}
}
OUTPUT
Page 12
Course II_BCA NEP Syllabus
2. Program to handle Null Pointer Exception and use the “finally” method to
display a message to the user.
public class NPException
{
public static void main(String[] args) {
String s=null;
try{
System.out.println(s.length());
}catch(NullPointerException e)
{
System.out.println(e);
}
finally{
System.out.println("This will always executes");
}
Output
java.lang.NullPointerException
This will always executes
Happy Coding
Page 13