0% found this document useful (0 votes)
24 views13 pages

UNIT3 - Java

1) Exception handling in Java allows programs to handle errors and unexpected events gracefully to prevent program termination. There are three types of exceptions: checked exceptions, unchecked exceptions, and errors. 2) The try block contains code that might throw exceptions. It is followed by catch blocks that handle specific exceptions or a finally block that contains cleanup code. 3) Custom exceptions can be created by extending the Exception class to handle application-specific exceptions.

Uploaded by

hihekab436
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views13 pages

UNIT3 - Java

1) Exception handling in Java allows programs to handle errors and unexpected events gracefully to prevent program termination. There are three types of exceptions: checked exceptions, unchecked exceptions, and errors. 2) The try block contains code that might throw exceptions. It is followed by catch blocks that handle specific exceptions or a finally block that contains cleanup code. 3) Custom exceptions can be created by extending the Exception class to handle application-specific exceptions.

Uploaded by

hihekab436
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Exception Handling in Java

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

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

Page 2
Exception Handling in Java

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.

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

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

Example Program1

Example Program2

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

Page 6
Exception Handling in Java

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

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

else

[Link]("Eligible for voting");

public static void main(String args[])

checkAge(13);

[Link]("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;

public static void main(String args[]){

try{

Page 8
Exception Handling in Java

[Link](division(15,0));

catch(ArithmeticException e){

[Link]("You shouldn't divide number by zero");

Example program2

class ThrowsExecp

static void fun() throws IllegalAccessException

[Link]("Inside fun(). ");

throw new IllegalAccessException("demo");

public static void main(String args[])

{ try

fun();

Page 9
Exception Handling in Java

catch(IllegalAccessException e)

[Link]("caught in main.");

[Link]("END OF PROGRAM ");

Custom Exception

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


class that belongs to [Link] 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
Exception Handling in Java

public class MainException { public

static void main(String args[]) {

try {

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

} catch(CustomException e) {

[Link](e);

Output

Custom Exception Occurred : This is a custom message

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


when the array is initialized to negative values.

Page 11
Exception Handling in Java

public class NegetiveArrayException{


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

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


} catch (NegativeArraySizeException e) {

[Link](e);

}
[Link]("Continuing execution...");
}
}
OUTPUT

2. Program to handle Null Pointer Exception and use the “finally” method to display a
message to the user.
public class NPException
Page 12
Exception Handling in Java

{
public static void main(String[] args) {
String s=null; try{
[Link]([Link]());
}catch(NullPointerException e)
{

[Link](e);
}
finally{
[Link]("This will always executes");
}

[Link](“Happy Coding ");


}
}

Output

[Link]
This will always executes
Happy Coding

Page 13

Common questions

Powered by AI

Method signatures with the 'throws' keyword inform the callers of a method about the exceptions it might throw, allowing them to prepare for potential exception handling. This clarity ensures that exceptions are recognized in advance, and proper handling measures such as try-catch blocks can be implemented .

The 'try' block in Java contains the set of statements that might throw an exception. It must be used within a method and requires a following 'catch' or 'finally' block (or both) to handle any thrown exceptions, ensuring that the program continues execution .

Custom exceptions in Java allow programmers to create exceptions that provide specific error-handling and messaging suitable for particular application needs. They are implemented by extending the Exception class, enabling developers to define detailed exception messages and behaviors, as seen with class CustomException .

The main purpose of exception handling in Java is to manage exceptions that disrupt the normal flow of a program, allowing the program to continue executing beyond the error point rather than terminating abnormally .

Incorrect use of the 'throw' keyword can lead to runtime errors and program crashes if the thrown exception is not suitably caught and handled, especially for unchecked exceptions, potentially making the codebase more error-prone and less stable .

A multi-catch block improves efficiency by allowing a single catch block to handle multiple exceptions types, thereby reducing the need for multiple catch blocks and simplifying code maintenance. Each catch block contains different exception handlers, enabling the program to handle various exceptions efficiently .

Unchecked exceptions can negatively impact the reliability of a Java program because they occur at runtime and are not identified until the code is executed, leading to potential program crashes if not properly handled. This unpredictability requires developers to anticipate exception scenarios to ensure robustness .

The 'throws' keyword in Java indicates that a method may throw specified exceptions, obligating caller methods to handle these exceptions via try-catch blocks. For example, a method declared with 'throws ArithmeticException' indicates that it might throw this exception during execution .

Checked exceptions are those that are checked at compile-time, such as IOException and SQLException, directly inheriting from Throwable except for RuntimeException and Error. Unchecked exceptions occur at runtime, like ArithmeticException and NullPointerException, as they inherit from RuntimeException .

The 'finally' block provides a mechanism to execute crucial code irrespective of whether an exception is handled. It is used to close resources or clean up actions, such as closing connections, which ensures that resources are properly released even if an exception occurs .

You might also like