Skip to content
Related Articles

Related Articles

Improve Article

ClosedChannelException in Java with Examples

  • Last Updated : 01 Oct, 2021

The class ClosedChannelException is invoked when an I/O operation is attempted on a closed channel or a channel that is closed to the attempted operation. That is if this exception is thrown, however, does not imply the channel is completely closed but is closed to the attempted operation.

Syntax:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

public class ClosedChannelException
extends IOException

The hierarchy of ClosedChannelException is as follows:



Now let us do see constructor details of this class before proceeding to it’s methods.

ConstructorDescription
ClosedChannelException()Constructs an instance of the class

Now let us discuss the methods inherited from Throwable class. They are depicted in tabular format below ias follows:

MethodDescription
addSuppressed(Throwable exception)Add this exception to the exceptions that were suppressed so that this exception could be dispatched.
fillInStackTrace()Records within this Throwable object information about the current state of the stack frame for the current thread and fills in the execution stack trace.
getCause()Returns the cause of this Throwable or null if the cause is unknown.
getLocalizedMessage()Returns a localized description of this Throwable. Subclasses may override the description. If the subclass doesn’t override this method then the result will be the same as that of getMessage().
getMessage()Return the detailed message description of this Throwable.
getStackTrace()Returns an array of stack trace elements, each representing one stack frame. Gives access to the stack trace information printed by printStackTrace().
getSuppressed()Returns an array containing all the exceptions that were suppressed in order to dispatch this exception.
initCause(Throwable cause)Initializes the cause of this Throwable with the given value.
printStackTrace()Prints this Throwable and its backtrace on the error output stream.
printStackTrace(PrintStream s)Prints this Throwable and its backtrace on the specified PrintStream.
printStackTrace(PrintWriter s)Prints this Throwable and its backtrace to the specified PrintWriter.
setStackTrace(StackTraceElement[] stackTrace)Sets the stack trace elements of this Throwable. It is designed for Remote Procedure Call Frameworks and advanced systems, it allows the client to override the default stack trace. 
toString()Returns a short description of this Throwable in the format, Name of the class of this object: Result of invoking the object’s getLocalizedMessage(). If getLocalizedMessage() returns null, then only the class name is returned.

Note: this refers to the object in whose context the method is being called.

Implementation: We are essentially going to create a channel, closing it, and then trying to perform a read operation on a closed channel. This will trigger the ClosedChannelException. The steps are as follows:

  1. We will create an instance of RandomAccessFile class to open a text file from your system in “rw” i.e read-write mode.
  2. Now we create a channel to the opened file using FileChannel class.
  3. After that, we create a buffer to read bytes of data from this channel using ByteBuffer class.
  4. Further, Charset class, we define the encoding scheme as “US-ASCII”.
  5. Finally, before we start the process of reading this file, we close the channel.

Therefore, when a read operation is attempted on this channel a ClosedChannelException is thrown. We catch the Exception in the catch block where you may add any Exception handling that is specific to your requirement, here we are only printing a message.

Example

Java




// Java Program to Illustraye Working of
// ClosedChannelException
 
// Importing required classes
// Input output classes
import java.io.IOException;
import java.io.RandomAccessFile;
// Classes from java.nio package
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
 
// Main class
// For ClosedChannelException
public class GFG {
 
    // Main driver method
    public static void main(String args[])
        throws IOException
    {
 
        // Try block to check for exceptions
        try {
 
            // Open a file in your system using the
            // RandomAccessFile class Custom local directory
            // on machine
            RandomAccessFile randomAccessFile
                = new RandomAccessFile(
                    "D:/Documents/textDoc.txt", "rw");
 
            // Now creating a channel using the FileChannel
            // class to the file opened using the
            // RandomAccessFile class
            FileChannel fileChannel
                = randomAccessFile.getChannel();
 
            // Create a buffer to read bytes from the
            // channel using the ByteBuffer class
            ByteBuffer byteBuffer
                = ByteBuffer.allocate(512);
            Charset charset = Charset.forName("US-ASCII");
 
            // Close the file channel
            // We do this so the exception is thrown
            fileChannel.close();
 
            // Try to read from the fileChannel which is now
            // closed
            while (fileChannel.read(byteBuffer) > 0) {
 
                byteBuffer.rewind();
                System.out.print(
                    charset.decode(byteBuffer));
                byteBuffer.flip();
            }
 
            // Closing the connections to free up memory
            // resources using close() method
            randomAccessFile.close();
        }
 
        // Catch block to handle the exceptions
 
        // Handling Application specific Exception
        catch (ClosedChannelException e) {
 
            // Print message if exception is occured
            System.out.println(
                "ClosedChannelException has occurred");
        }
    }
}

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :