Home / Computer Science / Java Language / Exception Handling In Java

Exception Handling In Java

In this Article we are discussing about theExceptions and how to handle our custom exceptions in java.

First we need to know about the what is Exception and what is Error?

Exception is an abnormal condition which stops the execution of the program but an Error is sub class of Throwable which indicates serious problems of the program.

See the below image for better understanding about the Hierarchy of Exception classes in java.

Exception Handling
Exception Handling Classes and Heirarchy

Exception may occur at different reasons such as like below.

1. User enters wrong input/ invalid input.

2. Necessary file not found or cannot found.

In java Exceptions may solve by using try, catch and finally blocks.

Used key words in java for handling Exceptions:

try, catch, finally, throw, throws.

public class Exception extends Throwable The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor’s throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

Exceptions can be classified in two ways.

1 1. Checked Exceptions

2. Unchecked Exceptions.

An unchecked exceptions, such as an ArithmeticException caused by attempting integer division

by 0, a NumberFormatException, or a NullPointerException, does not have to be handled with a try and catch block.

Checked Exceptions also known as Compile time Exceptions because these are occurs at Compile time.

These exceptions are cannot ignored, unless these are fixed programmer does not execute the program.

For example FileNotFoundException.

Syntax:

class A {

public static void main(String args[]){

try{

statements;

}catch(Exception e){

statements;

}finally{

statements;

}

}

}

1. public Exception() – Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be initialized by a call to Throwable.initCause(java.lang.Throwable)

2. public Exception(String message)- Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to Throwable.initCause(java.lang.Throwable)

Parameters:

message – the detail message. The detail message is saved for later retrieval by the Throwable.getMessage() method

3. public Exception(String message,Throwable cause)

Constructs a new exception with the specified detail message and cause. Note that the detail message associated with cause is not automatically incorporated in this exception’s detail message.

Parameters:

message – the detail message (which is saved for later retrieval by the Throwable.getMessage() method).

cause – the cause (which is saved for later retrieval by the Throwable.getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)

Since:

1.4

4. public Exception(Throwable cause)

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause). This constructor is useful for exceptions that are little more than wrappers for other throwables (for example, PrivilegedActionException).

Parameters:

cause – the cause (which is saved for later retrieval by the Throwable.getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)

Since:

1.4

5. protected Exception(String message, Throwable cause,

boolean enableSuppression,boolean writableStackTrace)

Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.

Parameters:

message – the detail message.

cause – the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.)

enableSuppression – whether or not suppression is enabled or disabled

writableStackTrace – whether or not the stack trace should be writable

Since:

1.7


Methods For Exception handling in java:

1. public String getMessage() – it returns string, the message is about the exception which occurs. This message is initialized in the Throwable constructor.

2. public Throwable getCause() – it returns the problem of the exception which is represented for Throwable object.

3. public void printStackTrace() – it return the toString(), returns the result of error output stream.

4. public StackTraceElement[] getStackTrace() – Provides programmatic access to the stack trace information printed by printStackTrace(). Returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assuming the array’s length is non-zero) represents the top of the stack, which is the last method invocation in the sequence. Typically, this is the point at which this throwable was created and thrown. The last element of the array (assuming the array’s length is non-zero) represents the bottom of the stack, which is the first method invocation in the sequence.

5. public Throwable initCause(Throwable cause) -Initializes the cause of this throwable to the specified value. (The cause is the throwable that caused this throwable to get thrown.)

This method can be called at most once. It is generally called from within the constructor, or immediately after creating the throwable. If this throwable was created with Throwable(Throwable) or Throwable(String,Throwable), this method cannot be called even once.

An example of using this method on a legacy throwable type without other support for setting the cause is: try {

lowLevelOp();

} catch (LowLevelException le) {

throw (HighLevelException)

new HighLevelException().initCause(le);

// Legacy constructor

}

6. public String toString() – Returns a short description of this throwable. The result is the concatenation of:

the name of the class of this object

“: ” (a colon and a space)

the result of invoking this object’s getLocalizedMessage() method If getLocalizedMessage returns null, then just the class name is returned.

Try with ARM (Automatic Resource Management) In java. A New Feature in JavaSE8.

Try with Resource management:

In the previous post we are learning what is exception and how to handle the How to handle exception in java.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {

try (BufferedReader br =

new BufferedReader(new FileReader(path))) {

return br.readLine();

}

}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Program Snip1:

FileInputStream fis = new FileInputStream(…);
try {
// … use stream
}
catch(IOException e) {
// handle exception
} finally {
try {
if(fis != null) {
fis.close();
}
} catch(IOException e) {
// handle another possible exception
}
}

Program Snip2:

try (FileInputStream fis = new FileInputStream (…)){
// … use stream
} catch(IOException e) {
// handle exception
}

See the difference between these two program snips in the second program snip try followed with braces and in program snip1 don’t have.

In this the resource is an object once the usage of the object is done it is automatically closed. For example in data base connection, connection is automatically closed.

See the below Example:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithARM {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader(“C:\\try.txt”))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}

Advantages of Automatic Resource Management:

More readable and flexible.

Reduce the code.

No need to write finally block because resources are managed in try().

Multiple resources are handled by using semicolon in try catch.

Resources are managed automatically.

About GSK

Hi, i am Santosh Gadagamma, a tutor in Software Engineering and an enthusiast for sharing knowledge in Computer Science and other domains. I developed this site to share knowledge to all the aspirants of technologies like, Java, C/C++, DBMS/RDBMS, Bootstrap, Big Data, Javascript, Android, Spring, Hibernate, Struts and all levels of software project design, development, deployment, and maintenance. As a programmer I believe that, "The world now needs computers to function." Hope, this site guides you as a learning tool towards greater heights. I believe that Education has no end points and i wish to learn more in the process of teaching you.

Check Also

StringBuffer in Java

A string buffer is similar to String, but the difference is string cannot be modified …