ClosedChannelException in Java with Examples Last Updated : 16 Feb, 2022 Comments Improve Suggest changes Like Article Like Report 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: 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. ConstructorDescriptionClosedChannelException()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: MethodDescriptionaddSuppressed(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: We will create an instance of RandomAccessFile class to open a text file from your system in “rw” i.e read-write mode.Now we create a channel to the opened file using FileChannel class.After that, we create a buffer to read bytes of data from this channel using ByteBuffer class.Further, Charset class, we define the encoding scheme as “US-ASCII”.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 Illustrate 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 occurred System.out.println( "ClosedChannelException has occurred"); } } } Output: Comment More infoAdvertise with us Next Article ClosedChannelException in Java with Examples M ManasiKirloskar Follow Improve Article Tags : Java Java Programs Java-Exceptions Practice Tags : Java Similar Reads Types of Errors in Java with Examples Error is an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed befo 8 min read Java Program to Handle Checked Exception Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error.  ClassNotFoundExcept 5 min read User Defined Exceptions using Constructors in Java In Java, we have already defined, exception classes such as ArithmeticException, NullPointerException etc. These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException. In Java, we can create our own exception class an 3 min read java.io.FileNotFoundException in Java java.io.FileNotFoundException which is a common exception which occurs while we try to access a file. FileNotFoundExcetion is thrown by constructors RandomAccessFile, FileInputStream, and FileOutputStream. FileNotFoundException occurs at runtime so it is a checked exception, we can handle this excep 4 min read How to Handle a java.lang.ArithmeticException in Java? In Java programming, the java.lang.ArithmeticException is an unchecked exception of arithmetic operations. This means you try to divisible by zero, which raises the runtime error. This error can be handled with the ArthmeticException. ArithmeticException can be defined as a runtime exception that ca 2 min read How to Solve IllegalArgumentException in Java? An unexpected event occurring during the program execution is called an Exception. This can be caused due to several factors like invalid user input, network failure, memory limitations, trying to open a file that does not exist, etc. If an exception occurs, an Exception object is generated, contai 3 min read Using throw, catch and instanceof to handle Exceptions in Java Prerequisite : Try-Catch Block in Java In Java, it is possible that your program may encounter exceptions, for which the language provides try-catch statements to handle them. However, there is a possibility that the piece of code enclosed inside the 'try' block may be vulnerable to more than one ex 4 min read Java Program to Handle the Exception Hierarchies Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program and terminates the program. Exception Handling: The process of dealing with exceptions is known as Exception Handling. Hierarchy of Exceptions: 4 min read How to Fix "class, interface, or enum expected" Error in Java with Examples? In Java, the class interface or enum expected error is a compile-time error. There can be one of the following reasons we get âclass, interface, or enum expectedâ error in Java: Case 1: Extra curly Bracket Java class Hello { public static void main(String[] args) { System.out.println("Helloworld"); 2 min read Java Program to Handle Runtime Exceptions RuntimeException is the superclass of all classes that exceptions are thrown during the normal operation of the Java VM (Virtual Machine). The RuntimeException and its subclasses are unchecked exceptions. The most common exceptions are NullPointerException, ArrayIndexOutOfBoundsException, ClassCastE 2 min read Like