Category: Exceptions

java.nio.file.AccessDeniedException

java.lang.Object
    java.lang.Throwable
        java.lang.Exception
            java.io.IOException
                java.nio.file.FileSystemException
                    java.nio.file.AccessDeniedException

AccessDeniedException is a  Checked exception thrown when a file system operation is denied. Typically due to a file permission or other access check.

Below is an example where this Exception is thrown by the Files.write() method because it can’t find a file at “C:\\test\\” directory.

Path path = Paths.get("C:\\test\\");

try {
	Files.write(path, new byte[] {127,0,0,1}); //will throw java.nio.file.AccessDeniedException
} catch (IOException e) {
	e.printStackTrace();
}

//console
/* 
java.nio.file.AccessDeniedException: C:\test
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.spi.FileSystemProvider.newOutputStream(Unknown Source)
at java.nio.file.Files.newOutputStream(Unknown Source)
at java.nio.file.Files.write(Unknown Source)
at test2.Main.main(Main.java:21)
*/
Filed under: Exceptions, JavaTagged with: , , , ,

RuntimeException in Java

RuntimeException is a sublclass of Exception that can be extended to create unchecked Exceptions.

noffa

Unchecked Exceptions are those Exceptions that don’t have to be caught on compile time, where as Checked Exceptions do have to be caught on compile time.

A NullPointerException is a subclass of RuntimeExceprion. You aren’t required to catch a NullPointerException.

Object a = null;
a.toString(); // throws NullPointerException

A IOException is direct subclass of Exception so it is a Checked Exception and you are required to catch it.

try {
    //thorows IOException
    FileReader fr = new FileReader(filePath);
} catch (IOException e) {
    e.printStackTrace();
}

 

Filed under: Exceptions, JavaTagged with: , ,