0% found this document useful (0 votes)
4 views

Java

Java

Uploaded by

jb5545121
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java

Java

Uploaded by

jb5545121
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Course II_BCA NEP Syllabus

Exception Handling in 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.

Suppose there are 10 statements in a Java program and an exception occurs at


statement 5; the rest of the code will not be executed,

An exception can occur for many reasons. Some of them are:

 Invalid user input


 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file

Page 1
Course II_BCA NEP Syllabus

Types of Java Exceptions


There are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

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

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

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

Java catch block


Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the parent class
exception ( i.e., Exception) or the generated exception type. However, the good
approach is to declare the generated type of exception.

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


Java finally block is always executed whether an exception is handled or not.

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

public class JavaTester{

public void checkAge(int age){

if(age<18)

Page 7
Course II_BCA NEP Syllabus

throw new ArithmeticException("Not Eligible for voting");

else

System.out.println("Eligible for voting");

public static void main(String args[])

checkAge(13);

System.out.println("End Of Program");

throws

throws is a keyword in Java which is used in the signature of method to indicate


that this method might throw one of the listed type exceptions. The caller to these
methods has to handle the exception using a try-catch block.

Example program1

public class JavaTester{

public int division(int a, int b) throws ArithmeticException

int t = a/b;

return t;

Page 8
Course II_BCA NEP Syllabus

public static void main(String args[]){

try{

System.out.println(division(15,0));

catch(ArithmeticException e){

System.out.println("You shouldn't divide number by zero");

Example program2

class ThrowsExecp

static void fun() throws IllegalAccessException

System.out.println("Inside fun(). ");

throw new IllegalAccessException("demo");

public static void main(String args[])

try

fun();

Page 9
Course II_BCA NEP Syllabus

catch(IllegalAccessException e)

System.out.println("caught in main.");

System.out.println("END OF PROGRAM ");

Custom Exception

 we can create our own exceptions by extending the buit-in


Exception class that belongs to java.lang package. And Creating
our own Exception is known as custom exception or user-defined
exception.
 Basically, Java custom exceptions are used to customize the
exception according to user need.

class CustomException extends Exception {

String message;

CustomException(String str) {

message = str;

public String toString() {

return ("Custom Exception Occurred : " + message);

Page 10
Course II_BCA NEP Syllabus

public class MainException {

public static void main(String args[]) {

try {

throw new CustomException("This is a custom message");

} catch(CustomException e) {

System.out.println(e);

Output

Custom Exception Occurred : This is a custom message

Page 11
Course II_BCA NEP Syllabus

1. Program to catch Negative Array Size Exception. This exception is


caused when the array is initialized to negative values.

public class NegetiveArrayException{


public static void main(String[] args) {
try {

int[] array = new int[-5];


} catch (NegativeArraySizeException e) {

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");
}

System.out.println(“Happy Coding ");


}
}

Output

java.lang.NullPointerException
This will always executes
Happy Coding

Page 13

You might also like