Professional Documents
Culture Documents
•It is Character Streaming.
Java.io.File Class in Java
•The File class contains several methods for working with the
path name, deleting and renaming files, creating new
directories, listing the contents of a directory, and determining
several common attributes of files and directories.
defines an abstract file name for the ‘newfile’ file in directory /usr/local/bin.
JAVA File methods
Eg: Dividing an integer by zero , Accessing an element that is out of bounds of an array,
Trying to store a value into an array of incompatible class or type.
When Java interpreter encounters an error, it creates an
exception object and throws it.
If the exception object is not caught and handled properly,
the interpreter will display an error message and terminate
the program.
A Java exception is an object that describes an exceptional
(that is, error) condition that has occurred in a piece of
code.
It allows you to fix the error.
It prevents the program from automatically terminating.
To guard against and handle a run-time error, simply enclose the code that
needs to be monitored inside a try block.
Immediately following the try block, include a catch clause that specifies
the exception type that you wish to catch.
The try block can have one or more statements that could generate an
exception.
If any one statement that generates an exception, the remaining
statements in the block are skipped and execution jumps to the catch
block that is placed next to the try block.
General Form:
try
{
// block of code to monitor for errors
}
catch (ExceptionType exOb)
{
// exception handler for ExceptionType1
}
// ...
finally
{
//
block
of
code
to be
exec
class Ex {
public static void main(String args[]) {
int d, a;
try
{
// monitor a block of code.
d = 0;
a = 42 / d;
} System.out.println("This
will not be printed.");
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}}
Output:
Division by zero.
After catch statement.
Throws
class Throws {
static void throwOne( ) throws
IllegalAccessException
{
System.out.println("Inside throwOne."); throw new
IllegalAccessException("demo");
}
public static void main(String args[ ]) { try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}}
Note:
// A throws clause lists
the types of exceptions that a method
OUTPUT:
inside throwOne
caught java.lang.IllegalAccess Exception: demo
Finally
finally creates a block of code that will be executed after a try/catch
block has completed and before the code following the try/catch
block.
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no
catch statement matches the exception.
The finally clause is optional.
END