Professional Documents
Culture Documents
Exceptions
Exceptions
Example:
class RunTimeErrorDemo {
public static void main(String args[]) {
int arr[] = new int[4];
arr[5] = 100;
System.out.println("Success");
}}
Compile Time Error:
Errors that occur during compiling the program
and if there any syntax error in the program
like missing semicolon at the end of a
statement or curly braces etc., then the Java
compiler displays the error on to the screen.
Example:
class CompileTimeDemo {
public static void main(String as[])
int i=10; j=20;
System.out.println(i)
} }
Logical Error:
In Java logical error is nothing but when a program is
compiled and executed without any error but not producing
any result is called as logical error.
These errors can’t be detected by neither compiler nor JVM.
This errors occur due to poor logic written by the programmer.
Java - Exceptions
An exception (or exceptional event) is a problem that arises
during the execution of a program.
When an Exception occurs the normal flow of the program is
disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to
be handled.
Reasons for Exceptions to occur
Error class:
Exceptions of type Error are related to errors that occur in the java
virtual machine itself, and not in our program.
These types of exceptions are beyond our control, and our program
will not handle them. Normally programs cannot recover from
error. Example: OutOfMemoryError and UnknownError.
Exception Class:
Here the programs can handle the exceptions that occur at the time
of compiling and running the program.
Two types of subclasses
1) RuntimeExceptions or Unchecked Exceptions
Unchecked Exceptions or Runtime Exceptions
• The unchecked exceptions are those exceptions that occur
during the execution of the program. Hence they are also
referred to as Runtime exceptions.
• These exceptions are generally ignored during the compilation
process. They are not checked while compiling the program.
• The exception objects for which compiler does not compel to
handle them is known as unchecked exceptions.
Checked Exceptions
• Checked exceptions are also known as compile-time exceptions
as these exceptions are checked by the compiler during the
compilation process to confirm whether the exception is
handled by the programmer or not. If not, then the system
displays a compilation error.
• The Exception objects for which compiler compels to handle
then is known as checked exceptions.
Popular examples of Checked Exceptions:
IOException: While using file input/output stream related
exception
SQLException : While executing queries on database
related to SQL syntax
DataAccessException :Exception related to accessing
data/database
ClassNotFoundException : Thrown when the JVM
can’t find a class it needs, because of a command-line error, a
classpath issue, or a missing .class file
InstantiationException: Attempt to create an object of
an abstract class or interface.
InterruptedException : one tread has been interrupted
by another thread.
NoSuchFieldException : a requested field does not exist
Popular Unchecked Exceptions:
NullPointerException : Thrown when attempting to access
an object with a reference variable whose current value is null
ArrayIndexOutOfBound : Thrown when attempting to
access an array with an invalid index value (either negative or
beyond the length of the array)
IllegalArgumentException : Thrown when a method
receives an argument formatted differently than the method
expects.
IllegalStateException: Thrown when the state of the
environment doesn’t match the operation being attempted,e.g.,
using a Scanner that’s been closed.
NumberFormatException : Thrown when a method that
converts a String to a number receives a String that it cannot
convert.
ArithmaticException: Arithmetic error, such as divide-by-
zero.
Exception Handling in java
class Main {
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
}}}
Output
ArithmeticException => / by zero
• In the example, we are trying to divide a number by 0.
Here, this code generates an exception.
• To handle the exception, we have put the code, 5 / 0
inside the try block. Now when an exception occurs, the
rest of the code inside the try block is skipped.
• The catch block catches the exception and statements
inside the catch block is executed.
• If none of the statements in the try block generates an
exception, the catch block is skipped.
• If an error occurs in the try block, then JVM creates an
object of corresponding exception class and throws it .
The catch block will receive the reference and handles
appropriately.
Multiple Catch Block
• In Java, a single try block can have multiple catch
blocks.
• When statements in a single try block generate
multiple exceptions, we require multiple catch
blocks to handle different types of exceptions.
• This mechanism is called multi-catch block in java.
• Each catch block is capable of catching a different
exception.
• That is each catch block must contain a different
exception handler.
try
{
statements;
}
catch(ExceptionType1 e1)
{
statements;
}
catch(ExceptionType2 e2)
{
statements;
}
catch(ExceptionType3 e3)
{
statements;
}
...
catch(ExceptionTypen en)
{
statements;
}
Output is -:
Exception Caught -
java.langArrayIndexOutOfBoundsException: 5
• Java multi-catch block acts as a case in a switch statement.
In the above syntax, if the exception object
(ExceptionType1) is thrown by try block, the first catch
block will catch the exception object thrown and the
remaining catch block will be skipped.
• In case, exception object thrown does not match with the
first catch block, the second catch block will check and so
on.
• At a time only one exception occurs and at a time only one
catch block is used
• In this code, we have three catch blocks associated with one try
block. At the runtime, code in try block throws an exception of
type ArrayIndexOutOfBoundsException, this exception type is
matched with the declared exception type in every catch-
block(matching starts with the first catch block).
• The catch block that matches with type of exception thrown is
executed, while the rest of catch blocks are skipped. Let's see how
-
• •••The first catch block declared an exception of type
ArrayStoreException, which doesn't match with the exception
ArrayIndexOutOfBoundsException thrown by the try block,
hence this catch-block is not executed.
• •••ArrayIndexOutOfBoundsException declared in the second
catch block matches with the exception
ArrayIndexOutOfBoundsException thrown by the try block and
hence second catch block will be executed.
•••As, we have already found the matching catch block, hence,
the third catch block with declared exception of type Exception is
skipped and not executed, even though Exception is superclass of
ArrayIndexOutOfBoundsException class.
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println ("Array Index is Out Of Bounds");
} } }
Exercise-2
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
int num = Integer.parseInt ("akki") ;
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
} } }
class Test{
Exercise-3
public static void main(String[] args) {
try
{
int a[]= {1, 2, 3, 4};
for (int i = 1; i <= 4; i++)
{
System.out.println ("a[" + i + "]=" + a[i] + "n");
}
}
catch (Exception e)
{
System.out.println ("error = " + e);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println ("ArrayIndexOutOfBoundsException");
} }
}
Exercise-4
class Test{
public static void main (String[] args) {
try
{
int a = 0;
System.out.println ("a = " + a);
int b = 20 / a;
System.out.println ("b = " + b);
}
catch(ArithmeticException e)
{
System.out.println ("Divide by zero error");
}
finally
{
System.out.println ("inside the finally block");
} } }