CD Manual
CD Manual
Exception:
The runtime error which stop the normal flow of the program is called “Exception”.(or)
Exception is an abnormal condition .
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5,
the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we
perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.
1) Checked Exception
2) Unchecked Exception
3) Error
1) Checked Exception
A checked exception is an exception that is checked (notified) by the compiler at
compilation-time, these are also called as “compile time exceptions”.
These exceptions cannot simply be ignored, the programmer should take care of (handle)
these exceptions.
For example if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
Example
import java.io.*;
import java.io.FileReader;
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught
or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
2) Unchecked Exception
An unchecked exception is an exception that occurs at the time of execution. These are also
called as “Runtime Exceptions”.
Example: These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
If you have declared an array of size 5 in your program, and trying to call the 6 th element of the
array then an ArrayIndexOutOfBoundsException exception occurs.
Example
public class Unchecked_Demo {
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
3) Error
These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about
an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the
time of compilation.
1.try
2.catch
3.throw
4.throws
5.finally
1.try :The code which will raise the exception will be written in try block.
Syntax:
try
Ex:
try
int a=10,b=0;
int c=a/b;
2.catch:
The exception which is raised in try block will be catched by the catch block.
Syntax:
catch(Exceptiontype object)
//stmts
Ex:
catch(ArithmeticException e)
{
System.out.println(“The value of b should be greater than zero”);
Syntax:
Syntax:
throws ExceptionClass;
5.finally: A finally block contains all the crucial statements that must be executed whether
exception occurs or not.
The statements present in this block will always execute regardless of whether exception
occurs in try block or not
Syntax:
finally
//Set of statements
Example:
class Example
{
public static void main(String args[])
try
int num=121/0;
System.out.println(num);
catch(ArithmeticException e)
*/
finally
System.out.println("Out of try-catch-finally");
Output:
Example2:
class ExceptionHand
void Division()
try
int a=10,b=0;
if(b==0)
else
System.out.println("Division="+(a/b));
catch(ArithmeticException ae)
System.out.println("ArithmeticException caught");
void ArrayBounds()
{
try
System.out.println(Arr[6]);
catch(ArrayIndexOutOfBoundsException e)
System.out.println("ArrayoutofboundsException caught");
class ExceptionHandDemo
obj1.Division();
obj1.ArrayBounds();
}
Exception Models in Java
In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java supports are as follows.
Termination Model
Resumptive Model
Termination Model
In the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the type
of exception encountered.
In other words we can say that in termination model the error is so critical there is no way to get
back to where the exception occurred.
Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the exception
handler is expected to do something to stable the situation, and then the faulting method is
retried. In resumptive model we hope to continue the execution after the exception is handled.
In resumptive model we may use a method call that want resumption like behavior. We may also
place the try block in a while loop that keeps re-entering the try block util the result is
satisfactory.
}
}
When we execute the above code, it produce the following output for the value a = 10 and b = 0.
In the above example code, we are not used try and catch blocks, but when the value of b is zero
the division by zero exception occurs and it caught by the default exception handler.
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and
the specified class cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an
object, but that the object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers
do not allow.
4 InstantiationException
5 InterruptedException
6 NoSuchFieldException
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at
compile time, a NoSuchMethodException occurs during reflection when we try to
access a method that does not exist.
1 ArithmeticException
2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.
3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of
object into an array of objects
4 AssertionError
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to
another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal
or inappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or
has attempted to notify other threads that wait on an object's monitor, without owning
the specified monitor.
8 IllegalStateException
9 IllegalThreadStateException
S. No. Exception Class with Description
10 IndexOutOfBoundsException
11 NegativeArraySizeException
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or
integer, but the format of the input string is not appropriate or illegal.
14 SecurityException
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is
either negative, or greater than the size of the string itself.
16 UnsupportedOperationException
Using custom exceptions, we can define our exceptions as per our needs.
We may create constructor in the user-defined exception class and pass a string to
Exception class constructor using super().
The following example shows the custom exception that we defined for an Integer value.
//custom exception definition
Import java.io.*;
InvalidValueException(String s)
super(s);
class Main
if(int_val<10)
else
System.out.println("This is valid integer");
try
validate(9);
//validate(12);
catch(Exception m)
Output
Example2:
import java.util.Scanner;
class NotEligibleException extends Exception{
NotEligibleException(String msg){
super(msg);
}
}
class VoterList{
int age;
VoterList(int age){
this.age = age;
}
void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
public static void main(String args[]) {
implements Serializable
Constructors: Any class can have any one of the three or all the three types of
constructors. They are default, parameterized and non-parameterized constructors. This
class primarily has the following constructors defined:
Public Constructors
1. Throwable(): It is a non-parameterized constructor which constructs a new
Throwable with null as its detailed message.
2. Throwable(String message): It is a parameterized constructor which constructs
a new Throwable with the specific detailed message.
3. Throwable(String message, Throwable cause): It is a parameterized
constructor which constructs a new Throwable with the specific detailed
message and a cause.
4. Throwable(Throwable cause): It is a parameterized constructor which
constructs a new Throwable with the specific cause and a detailed message of
the cause by converting the case to the String using toString() method.
Protected constructors
1. Throwable(String message, Throwable cause, boolean enableSuppression, boolean
writableStackTrace):It Constructs a new throwable with the specified detail message,
cause, suppression enabled or disabled, and writable stack trace enabled or disabled.
The parameters are:-
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.
Methods: Apart from the above mentioned constructors, there are also many predefined
methods available in the throwable class. They are:
1. addSuppressed(Throwable exception): This method appends the specified exception to
the exceptions that were suppressed in order to deliver this exception.
Syntax:
Public final void addSuppressed(Throwable exception)
Returns: This method does not returns anything.
2. fillInStackTrace():Fills in the execution stack trace. This method records information
about the current state of the stack frames for the current thread within the current
Throwable object.
Syntax:
public Throwable fillInStackTrace ()
Returns: a reference to the current Throwable instance.
3. getCause(): It returns the cause that was supplied via one of the constructors requiring a
Throwable , or that was set after creation with the initCause() method.
Syntax:
public Throwable getCause ()
Returns: the cause of current Throwable. If the cause is nonexistent or unknown, it returns
null.
4. getLocalizedMessage(): This method creates a localized description of current
Throwable.
Syntax:
public String getLocalizedMessage ()
Returns: The localized description of current Throwable
5. getMessage():Returns the detail message string of current throwable.
Syntax:
public String getMessage ()
Returns: the detailed message string of current Throwable instance( may also return null)
6. getStackTrace(): This method provides programmatic access to the stack trace
information printed by printStackTrace(). It returns an array of stack trace elements, each
representing one stack frame. The zeroth element of the array (assume that the array’s
length is non-zero) is the last method invocation in the sequence. It also represents as the
top of the stack and 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) is the first method invocation
in the sequence and it represents the bottom of the stack.
Syntax:
public StackTraceElement[] getStackTrace ()
Returns: an array of stack trace elements representing the stack trace related to current
Throwable.
7. getSuppressed():Returns an array containing all of the exceptions that were suppressed,
in order to deliver this exception. If no exceptions were suppressed or suppression is
disabled, an empty array is returned.
Syntax: public final Throwable[] getSuppressed ()
Returns: an array containing all of the exceptions that were suppressed to deliver this
exception.
8. initCause(Throwable cause):Initializes the cause of current Throwable to the specified
value. This method can be called at most once. It is generally called from within the
constructor, or immediately after creating the throwable.
Syntax: public Throwable initCause (Throwable cause)
Parameters:
Throwable cause- the cause of current Throwable.
Throws:
1.IllegalArgumentException: This exception is thrown if cause is the current throwable,
because a throwable cannot be its own cause.
2. IllegalStateException: It occurs if this method has already been called on current
throwable.
Returns: a reference to current Throwable instance.
9. printStackTrace():Prints the current throwable and its backtrace to the standard error
stream.
Syntax: public void printStackTrace ()
Returns: This method returns nothing.
10. printStackTrace(PrintWriter s):Prints current throwable and its backtrace to the
specified print writer.
Syntax: public void printStackTrace (PrintWriter s)
Parameters: PrintWriter- It is the PrintWriter to use for output
Returns: This method returns nothing.
11. printStackTrace(PrintStream s):Prints current throwable and its backtrace to the
specified print stream.
Syntax: public void printStackTrace (PrintStream s)
Parameters: PrintStream- It is the PrintStream to use for output
Returns: This method returns nothing.
12. setStackTrace(StackTraceElement[] stackTrace):This method sets the stack trace
elements that will be returned by getStackTrace() and printed by printStackTrace() and
related methods.
Syntax: public void setStackTrace (StackTraceElement[] stackTrace)
Parameter: StackTraceElement- These are the stack trace elements to be associated with
current Throwable.
Throws:
NullPointerException- if stackTrace is null or if any of the elements of stackTrace are null
Returns:
This method returns nothing.
13. toString(): This method returns a short description of current throwable.
Syntax: public String toString ()
Returns: a string representation of current throwable.
Below program demonstrates the toString() method of Throwable class:
Java
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
throws Exception
{
try {
testException();
}
catch (Throwable e) {
Output:
Exception:
java.lang.Exception:
New Exception Thrown
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
throws Exception
{
try {
catch (ArithmeticException e) {
System.out.println(
"Message String = "
+ e.getMessage());
}
}
int c = a / b;
System.out.println("Result:" + c);
}
}
Output:
Message String = / by zero
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Points to remember
At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Example
MultipleCatchBlock.java
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Example
Let's see an example where we place a try block within another try block for two different
exceptions.te
System.out.println("normal flow..");
}
}
Output:
Note:
When any try block does not have a catch block for a particular exception, then the catch
block of the outer (parent) try block are checked for that exception, and if it matches, the
catch block of outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then the
Java runtime system will handle the exception. Then it displays the system generated
message for that exception.
I/O Streams in Java
Stream
Def:A logical connection between java program and a file(to which
we can send the data and from which we can read the data) is called
“Stream”.
The stream method helps to sequentially access a file. There are two
types of streams in Java-
Byte streams in Java are used to perform input and output operations
of 8-bit bytes while the Character stream is used to perform input and
output operations for 16-bits Unicode.
Character streams are useful in reading or writing text files which are
processed character by character. Byte Streams are useful to
read/write data from raw binary files.
An I/O (Input/Output) stream is used to represent an input source or
an output destination. It can represent many kinds of sources and
destinations like disc files (systems that manage data on permanent
storage devices eg. hard disc or magnetic disc) or devices.
Byte Streams(or)Binary Streams in Java
Byte streams are used to perform input and output of 8-bit bytes.
They are used to read bytes from the input stream and write bytes to
the output stream. Mostly, they are used to read or write raw binary
data.
Java provides many byte stream classes, but the most common ones
are-
Syntax:
try
{
sourceStream = new FileInputStream("source.txt");
targetStream = new FileOutputStream ("destination.txt");
Java provides many character stream classes, but the most common
ones are- FileReader- It is used to read two bytes at a time from the
source. The following is the constructor to create an instance of
the FileReader class.
This example deals with the usage of Character Stream to copy the
contents of one file to another. In the example, we will create two
objects of the FileReader and the FileWriter classes. The source and
the destination files names are given as parameters to
the FileReader and the FileWriter classes respectively. Then the
content of the source file will be copied to the destination file.
import java.io.*;
public class CharacterStreamExample {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
// Reading source file using read method
// and write to file using write method
try {
in = new FileReader("source.txt");
out = new FileWriter("destination.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Reading Characters
read() method is used with BufferedReader object to read characters.
As this function returns integer type value has we need to use
typecasting to convert it into char type.
Int read()throwsIOException
classCharRead
publicstaticvoidmain(Stringargs[])
{
BufferedReaderbr=newBufferedreader(newInputstreamReader(Syste
m.in));
String readLine()throwsIOException
Import java.io.*;
classMyInput
publicstaticvoidmain(String[]args)
String text;
InputStreamReaderisr=newInputStreamReader(System.in);
BufferedReaderbr=newBufferedReader(isr);
text=br.readLine();//Reading String
System.out.println(text);
importjava.Io*;
classReadTest
publicstaticvoidmain(String[]args)
try
Filefl=newFile("d:/myfile.txt");
BufferedReaderbr=newBufferedReader(newFileReader(fl));
Stringstr;
while((str=br.readLine())!=null)
System.out.println(str);
}
br.close();
fl.close();
catch(IOException e){
e.printStackTrace();
importjava.Io*;
classWriteTest
publicstaticvoidmain(String[]args)
try
Filefl=newFile("d:/myfile.txt");
FileWriterfw=newFileWriter(fl);
fw.write(str);
fw.close();
fl.close();
catch(IOException e)
{e.printStackTrace();}
java.io.serializable
ObjectInputStream
ObjectOutputStream
Java Marker interface
java.io.serializable
java.lang.Cloneable
java.rmi.Remote
java.util.RandomAccess
To implement serialization and deserialization, Java provides two
classes ObjectOutputStream and ObjectInputStream.
ObjectOutputStream class
ObjectInputStream class
Publicfinal
ObjectreadObject()throwsIOException,ClassNotFoundException
while serializing if you do not want any field to be part of object state
then declare it either static or transient based on your need and it
will not be included during java serialization process.
importjava.io.*;
classStudentinfoimplementsSerializable
String name;
int rid;
static String contact;
this.name = n;
this.rid= r;
this.contact= c;
classDemo
publicstaticvoidmain(String[]args)
try
Studentinfosi=newStudentinfo("Abhi",104,"110044");
FileOutputStreamfos=newFileOutputStream("student.txt");
ObjectOutputStreamoos=newObjectOutputStream(fos);
oos.writeObject(si);
oos.flush();
oos.close();
catch(Exception e)
System.out.println(e);
importjava.io.*;
classStudentinfoimplementsSerializable
String name;
int rid;
staticString contact;
this.name = n;
this.rid= r;
this.contact= c;
classDemo
publicstaticvoidmain(String[]args)
Studentinfosi=null;
try
FileInputStreamfis=newFileInputStream("/filepath/student.txt");
ObjectInputStreamois=newObjectInputStream(fis);
si=(Studentinfo)ois.readObject();
catch(Exception e)
e.printStackTrace();}
System.out.println(si.name);
System.out.println(si.rid);
System.out.println(si.contact);
Abhi
104
null
Contact field is null because,it was marked as static and as we have
discussed earlier static fields does not get serialized.
There are many ways to read data from the keyboard. For example:
o InputStreamReader
o Console
o Scanner
o DataInputStream etc.
InputStreamReader class
BufferedReader class
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
In this example, we are reading and printing the data until the user
prints stop.
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
String name="";
while(!name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop
String text=System.console().readLine();
System.out.println("Text is: "+text);
import java.io.Console;
class ReadPasswordTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
Enter password:
Password is: 123
Java Scanner
The Java Scanner class breaks the input into tokens using a delimiter
which is whitespace by default. It provides many methods to read and
parse various primitive values.
The Java Scanner class is widely used to parse text for strings and
primitive types using a regular expression. It is the simplest way to
get input in Java. By the help of Scanner in Java, we can get input
from the user in primitive types such as int, long, double, byte, float,
short, etc.
The Java Scanner class extends Object class and implements Iterator
and Closeable interfaces.
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Output:
Output:
Boolean Result: true
String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
import java.io.File;
// Displaying file property
class fileProperty {
public static void main(String[] args)
{
if (f.exists()) {
System.out.println("Is writable:"
+ f.canWrite());
System.out.println("Is readable" + f.canRead());
System.out.println("Is a directory:"
+ f.isDirectory());
System.out.println("File Size in bytes "
+ f.length());
}
}
}
Output:
File name :file.txt
Path: file.txt
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writable:true
Is readabletrue
Is a directory:false
File Size in bytes 20
Example 2: Program to display all the contents of a directory
Here we will accept a directory name from the keyboard and then
display all the contents of the directory. For this purpose, list()
method can be used as:
String arr[]=f.list();
In the preceding statement, the list() method causes all the directory
entries copied into the array arr[]. Then pass these array elements
arr[i] to the File object and test them to know if they represent a file
or directory.
// Java Program to display all
// the contents of a directory
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
System.out.println("Enter dirpath:");
String dirpath = br.readLine();
System.out.println("Enter the dirname");
String dname = br.readLine();
// if directory exists,then
if (f.exists()) {
// get the contents into arr[]
// now arr[i] represent either a File or
// Directory
String arr[] = f.list();