119864
119864
Error
Error is a critical condition that cannot be handled by the code of the program.
An error is caused due to lack of system resources.
Errors are unchecked type. They are checked at runtime.eg. OutOfMemoryError
Exception
An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated.
Exception is the exceptional situation that can be handled by the code of the program.
An exception is caused because of the code.
Types
1) Checked ExceptionThe classes that extend Throwable class are known as checked exceptions
e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception The classes that extend RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
1. try
2. catch
3. finally
4. throw
5. throws
try-catch block:
The try block contains set of statements where an exception can occur.
A try block must be followed by catch blocks or finally block or both.
Java catch block is used to handle the Exception.
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
Example 1:
import java.io.*;
public class ExcepTest {
Example2:
class JavaException {
public static void main(String args[]) {
int d = 0;
St. Joseph’s College of Engineering Page 2 of 20
CS 1303 Object Oriented Programming Department of CSE
int n = 20;
try {
int fraction = n / d;
System.out.println("This line will not be Executed");
} catch (ArithmeticException e) {
System.out.println("In the catch Block due to Exception = " + e);
}
System.out.println("End Of Main");
}
}
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
throw Keyword
throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub
classes can be thrown. Program execution stops on encountering throw statement, and the closest catch
statement is checked for matching type of exception.
Syntax :
throw ThrowableInstance
class Test
{
static void avg()
throws Keyword
Any method that is capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be
handled. A method can do so by using the throws keyword.
Syntax :
Example:
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
Built-in exceptions
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Java defines several other types of exceptions that relate to its various class libraries. Following is the list
of Java Unchecked RuntimeException.
1 ArithmeticException
Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
3 ArrayStoreException
Assignment to an array element of an incompatible type.
4 ClassCastException
Invalid cast.
5 IllegalArgumentException
6 IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked thread.
7 IllegalStateException
Environment or application is in incorrect state.
8 IllegalThreadStateException
Requested operation not compatible with the current thread state.
9 IndexOutOfBoundsException
Some type of index is out-of-bounds.
10 NegativeArraySizeException
Array created with a negative size.
11 NullPointerException
Invalid use of a null reference.
12 NumberFormatException
Invalid conversion of a string to a numeric format.
13 SecurityException
Attempt to violate security.
14 StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
15 UnsupportedOperationException
An unsupported operation was encountered.
1 ClassNotFoundException
Class not found.
2 CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable interface.
3 IllegalAccessException
Access to a class is denied.
4 InstantiationException
Attempt to create an object of an abstract class or interface.
5 InterruptedException
One thread has been interrupted by another thread.
7 NoSuchMethodException
A requested method does not exist.
Example:
ClassNotFoundException : This Exception is raised when we try to access a class whose definition is
not found.
// Java program to illustrate the
// concept of ClassNotFoundException
class Bishal {
} class Geeks {
} class MyClass {
public static void main(String[] args)
{
Object o = class.forName(args[0]).newInstance();
System.out.println("Class created for" + o.getClass().getName());
}
}
Output:
ClassNotFoundException
FileNotFoundException :
This Exception is raised when a file is not accessible or does not open.
// Java program to demonstrate
// FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String args[])
{
try {
NullPointerException :
This exception is raised when referring to the members of a null object. Null represents nothing
// Java program to demonstrate NullPointerException
class NullPointer_Demo {
public static void main(String args[])s
{
try {
String a = null; // null value
System.out.println(a.charAt(0));
}
catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
Output:
NullPointerException..
NumberFormatException : This exception is raised when a method could not convert a string into a
numeric format.
// Java program to demonstrate
// NumberFormatException
class NumberFormat_Demo {
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt("akki");
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output:
Number format exception
class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
Output:
Starting of try block
Catch Block
MyException Occurred: This is My error Message
Stack Trace
Stack Trace is a list of method calls from the point when the application was started to the point
where the exception was thrown. The most recent method calls are at the top.
StackTraceElement
An element in a stack trace, as returned by Throwable.getStackTrace(). Each element represents a
single stack frame. All stack frames except for the one at the top of the stack represent a method
invocation. The frame at the top of the stack represents the execution point at which the stack trace was
generated.
stack frame representation: (Constructor of StackTraceElement class)
StackTraceElement(String declaringClass, String methodName, String fileName,
intlineNumber);
Example:
Method of StackTraceElementclass
String getClassName(): Returns the class name of the execution point described by the invoking
StackTraceElement
String getFileName(): Returns the file name of the execution point described by the invoking
StackTraceElement.
intgetLineNumber(): Returns the source-code line number of the execution point described by
the invoking StackTraceElement.
String getMethodName(): Returns the method name of the execution point described by the
invoking StackTraceElement.
boolean equals(ob):
Returns try if the invoking StackTraceElement is as the one passed in ob. Otherwise it returns
false.
Syntax: public booleanequals(ob)
Returns: true if the specified object is
anotherStackTraceElement instance representing the same execution point as this instance.
Nested Try
Exception handlers can be nested within one another. A try, catch or a finally block can in turn contains
another set of try catch finally sequence. In such a scenario, when a particular catch block is unable to
handle an Exception, this exception is rethrown. This exception would be handled by the outer set of try
catch handler. Look at the following code for Example.
import java.util.InputMismatchException;
public class Nested {
public static void main(String[] args) {
try {
System.out.println("Outer try block starts");
try {
System.out.println("Inner try block starts");
int res = 5 / 0;
} catch (InputMismatchException e) {
System.out.println("InputMismatchException caught");
} finally {
System.out.println("Inner final");
}
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught");
} finally {
System.out.println("Outer finally");
}
}
}
Output
String readLine() It is used to read a single line of text from the console.
String readLine(String fmt, It provides a formatted prompt then reads the single line of text
Object... args) from the console.
char[] readPassword() It is used to read password that is not being displayed on the
console.
char[] readPassword(String fmt, It provides a formatted prompt then reads the password that is not
Object... args) being displayed on the console.
Console printf(String format, It is used to write a string to the console output stream.
Object... args)
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
}
System.out.println("Enter age:");
int age = scanner.nextInt();
System.out.println("Entered age: " + age);
scanner.close();
Program output
Enter age:
12
Entered age: 12
Byte Stream
Byte stream classes are used to perform reading and writing of 8-bit bytes. All byte stream classes are
descended from InputStream and OutputStream.
Methods Description
This method returns the number of bytes that can be read
int available()
from the input stream.
abstract int read() This method reads the next byte out of the input stream.
Methods Description
This method flushes the output steam by forcing out buffered
flush()
bytes to be written out.
This method writes byte(contained in an int) to the output
abstract write(int c)
stream.
write(byte[] b) This method writes a whole byte array(b) to the output.
This method closes this output stream and also frees any
close()
resources connected with this output stream.
Example
/*
Write character sequence to the console
*/
import java.io.IOException; // Import the IOException class from java.io package
class WriteToConsole {
public static void main(String[] args) {
try {
byte consoleOut[] = new byte[]{'J','a','v','a',};
System.out.write(consoleOut);
}
catch (IOException ex) {
St. Joseph’s College of Engineering Page 15 of 20
CS 1303 Object Oriented Programming Department of CSE
System.out.println("Caught IOException: " + ex);
}
}
}
import java.io.*;
public class CopyFile {
Example:
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);} } }
/*
Write character sequence output to the console using PrintWriter
*/
import java.io.*; // Import all file classes from java.io package
class TestPrintWriter {
public static void main(String[] args) {
char someData[] = new char[]{'J','a','v','a'};
char someData2[] = new char[]{'J','á','v','á'};
double d = 128.128;