java-exception
java-exception
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.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner
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.
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 −
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.");
}
}
}
try {
// Inner try block
arr[5] = 100; // This will cause
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Inner catch: Array index out of bounds");
}
import java.io.*;
AgeException(String message) {
super(message);
} else {
System.out.println("Valid age");
try {
} catch (AgeException e) {
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
Syntax:
java
CopyEdit
throw new ExceptionType("Message");
Example:
java
CopyEdit
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
}
5. throws
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