0% found this document useful (0 votes)
6 views12 pages

java-exception

The document provides an overview of Java exceptions, detailing their types (checked, unchecked, and errors) and the importance of exception handling in programming. It explains the mechanisms of handling exceptions using keywords like try, catch, throw, throws, and finally, along with examples of their usage. Additionally, it discusses the need for user-defined exceptions to manage specific application conditions effectively.

Uploaded by

omindurkar8
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)
6 views12 pages

java-exception

The document provides an overview of Java exceptions, detailing their types (checked, unchecked, and errors) and the importance of exception handling in programming. It explains the mechanisms of handling exceptions using keywords like try, catch, throw, throws, and finally, along with examples of their usage. Additionally, it discusses the need for user-defined exceptions to manage specific application conditions effectively.

Uploaded by

omindurkar8
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
You are on page 1/ 12

JAVA – EXCEPTIONS

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.

An exception can occur for many different reasons. Following are some scenarios
where an exception occurs.

 A user has entered an invalid data.

 A file that needs to be opened cannot be found.

 A network connection has been lost in the middle of communications or the


JVM has run out of memory

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner

Based on these, we have three categories of Exceptions.

 Checked exceptions − A checked exception is an exception that is checked

(notified) by the compiler at compilation-time, these are also called as compile


time exceptions. These exceptions cannot simply be ignored, the programmer
should take care of (handle) these exceptions.

 Unchecked exceptions − An unchecked exception is an exception that occurs

at the time of execution. These are also called as Runtime Exceptions. These
include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.

 Errors − These are not exceptions at all, but problems that arise beyond the

control of the user or the programmer. Errors are typically ignored in your
code because you can rarely do anything about an error. For example, if a stack
overflow occurs, an error will arise. They are also ignored at the time of
1

compilation.
Page
EXCEPTION HANDLING
 Default Exception Handling : Whenever inside a method, if an exception has

occurred, the method creates an Object known as Exception Object and hands it
off to the run-time system(JVM). The exception object contains name and
description of the exception, and current state of the program where exception
has occurred. Creating the Exception Object and handling it to the run-time
system is called throwing an Exception.There might be the list of the methods
that had been called to get to the method where exception was occurred. This
ordered list of the methods is called Call Stack.Now the following procedure
will happen.
 The run-time system searches the call stack to find the method that
contains block of code that can handle the occurred exception. The block
of the code is called Exception handler.
 The run-time system starts searching from the method in which exception
occurred, proceeds through call stack in the reverse order in which
methods were called.
 If it finds appropriate handler then it passes the occurred exception to it.
Appropriate handler means the type of the exception object thrown
matches the type of the exception object it can handle.

 If run-time system searches all the methods on call stack and couldn’t
have found the appropriate handler then run-time system handover the
Exception Object to default exception handler , which is part of run-time
system. This handler prints the exception information in the following
format and terminates program abnormally.

 Customized Exception Handling: Java exception handling is managed via

five keywords: try, catch, throw, throws, and finally. Briefly, here is how they
work. Program statements that you think can raise exceptions are contained
within a try block. If an exception occurs within the try block, it is thrown. Your
code can catch this exception (using catch block) and handle it in some rational
manner. System-generated exceptions are automatically thrown by the Java run-
time system. To manually throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be specified as such by a throws
clause. Any code that absolutely must be executed after a try block completes is
put in a finally block.

CATCHING EXCEPTIONS

A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. Code
within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following −

Synta // Protected code


x } catch (ExceptionName e1) {
// Catch block
try {
}
The code which is prone to exceptions is placed in the try block. When an
exception occurs, that exception occurred is handled by catch block
associated with it. Every try block should be immediately followed either
by a catch block or finally block.

A catch statement involves declaring the type of exception you are trying
to catch. If an exception occurs in protected code, the catch block (or
blocks) that follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is passed to the catch
block much as an argument is passed into a method parameter.

Example
public class MyClass {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[
10]);
} catch (Exception e) {
System.out.println("Something
went wrong.");
}
}
}

The output will be:


Something went wrong.
3
e
Why Nested try is Needed

 Sometimes, we might want to separately handle multiple risky operations


inside the same outer block.
 Each try block can handle different types of exceptions or logics
independently.
 The inner try block handles specific operations and exceptions without
interrupting the outer try block's flow.

public class NestedTryExample {


public static void main(String[] args) {
try {
// Outer try block
int[] arr = new int[3];

try {
// Inner try block
arr[5] = 100; // This will cause
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Inner catch: Array index out of bounds");
}

int result = 10 / 0; // This will cause ArithmeticException


} catch (ArithmeticException e) {
System.out.println("Outer catch: Cannot divide by zero");
}
}
}

Why Multiple Catch is Needed

 Multiple catch blocks allow handling different types of exceptions


separately.
 Each catch block can provide a specific solution for a specific exception.
 Prevents the program from handling all exceptions the same way, which
increases clarity and maintainability.

public class MultipleCatchExample {


public static void main(String[] args) {
try {
int[] numbers = new int[5];
numbers[5] = 10 / 0; // Causes ArithmeticException first
} catch (ArithmeticException e) {
System.out.println("Catch Block 1: Cannot divide by zero");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Catch Block 2: Array index out of bounds");
} catch (Exception e) {
System.out.println("Catch Block 3: General exception");
}
}
}

Why throw is Needed

 The throw keyword is used to explicitly throw an exception from your


code.
 It is helpful when you want to enforce certain rules or conditions.
 You can throw built-in exceptions or custom (user-defined) exceptions.

public class ThrowExample {


public static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
} else {
System.out.println("Access granted - You are eligible.");
}
}

public static void main(String[] args) {


checkAge(15); // This will throw an exception
}
}

Why throws is Needed

 The throws keyword is used in a method signature to declare that the


method may throw one or more exceptions.
 It informs the caller of the method that they must handle the exception
using try-catch or further declare it.
 It is typically used with checked exceptions (like IOException).

import java.io.*;

public class ThrowsExample {

// Method declaring that it throws IOException


public static void readFile() throws IOException {
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
System.out.println(br.readLine());
br.close();
}

public static void main(String[] args) {


try {
readFile(); // Call the method that may throw exception
} catch (IOException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

Why finally is Needed

 The finally block always executes whether an exception is thrown or not.


 It's used to write cleanup code such as:
o Closing files or database connections
o Releasing resources
o Logging final status

public class FinallyExample {


public static void main(String[] args) {
try {
int data = 10 / 0; // This will cause an exception
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
}

Why User-Defined Exceptions are Needed

 Built-in exceptions (like NullPointerException, IOException) don’t always


describe custom business rules.
 User-defined exceptions allow you to:
o Handle specific application conditions (like "invalid age", "salary
too low").
o Create more meaningful and readable error messages.
o Improve code maintainability and clarity in large applications.

// Creating custom exception by extending Exception

class AgeException extends Exception {

AgeException(String message) {

super(message);

public class UserDefinedExceptionExample {

// Method to validate age

static void validateAge(int age) throws AgeException {

if (age < 18) {


throw new AgeException("Age must be 18 or above");

} else {

System.out.println("Valid age");

public static void main(String[] args) {

try {

validateAge(15); // This will throw the custom exception

} catch (AgeException e) {

System.out.println("Caught Exception: " + e.getMessage());

What is Exception Handling in Java?

Exception handling is a mechanism in Java to detect, manage, and recover from


unexpected events (exceptions) that disrupt the normal flow of a program.
Instead of crashing, a Java program can catch and handle errors gracefully, often
providing meaningful messages or fallback actions.
✅Keywords in Exception Handling (with Detailed Explanation)
1. try

 The try block is used to wrap code that might cause an exception.
 Only one exception can be thrown per try block, but multiple catch blocks
can follow it.

Syntax:

java
CopyEdit
try {
// risky code
}

Example:

java
CopyEdit
try {
int result = 10 / 0; // May cause ArithmeticException
}

2. catch

 The catch block is used to handle exceptions thrown by the try block.
 You can use multiple catch blocks to handle different exception types
separately.

Syntax:

java
CopyEdit
catch (ExceptionType name) {
// code to handle the exception
}

Example:

java
CopyEdit
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}

3. finally

 The finally block contains code that must be executed whether an exception
is thrown or not.
 Commonly used for resource cleanup, such as closing files or releasing
memory.

Syntax:

java
CopyEdit
finally {
// cleanup code
}

Example:

java
CopyEdit
finally {
System.out.println("This block always executes.");
}

4. throw

 The throw keyword is used to manually throw an exception from a method


or block.
 You can throw either built-in exceptions or custom (user-defined)
exceptions.

Syntax:

java
CopyEdit
throw new ExceptionType("Message");

Example:
java
CopyEdit
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
}

5. throws

 The throws keyword is used in a method declaration to indicate that the


method may throw one or more exceptions.
 The calling method must handle or declare those exceptions.

Syntax:

java
CopyEdit
returnType methodName() throws ExceptionType1, ExceptionType2 {
// method code
}

Example:

java
CopyEdit
public void readFile() throws IOException {
FileReader fr = new FileReader("data.txt");
}

Keyword Purpose
try Defines block of code that might throw an exception
catch Handles specific exceptions thrown by try block
finally Executes important code regardless of exception occurrence
throw Manually throws an exception
throws Declares exception(s) that a method might throw

You might also like