Chapter 4.1
Chapter 4.1
Run-Time Error
Logic Error
4.1 Exception Handling in Java –Types of Errors
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.
class demo
{
public static void main(String[] args)
{
int i=10;
System.out.println(i)
}
}
4.1 Exception Handling in Java –Types of Errors
class demo
{
public static void main(String[] args)
{
int a[]=new int[4];
a[5]=10;
System.out.println("Success");
}
}
4.1 Exception Handling in Java –Types of Errors
3. Logic 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.
class demo
{
public static void main(String[] args)
{
int a=100;
int b=10;
int c= a*b;
System.out.println("a divide by b =>"+c);
}
}
4.1 Exception Handling in Java –Types of Exceptions
Not Checked at
Compile Time
Checked at Compile
Time
4.1 Exception Handling in Java –Types of Exceptions
1. Built in Exception:
Exceptions that are already available in Java libraries are referred
to as built-in exception.
1. Built in Exception:
The unchecked exceptions are
Checked exceptions are just opposite to
called compile-time exceptions the checked exceptions. The
because these exceptions are compiler will not check these
checked at compile-time by the exceptions at compile time.
compiler. The compiler ensures
whether the programmer In simple words, if a program
handles the exception or not. throws an unchecked exception,
and even if we didn't handle or
The programmer should have declare it, the program would not
to handle the exception; give a compilation error. Usually, it
otherwise, the system has shown occurs when the user provides bad
a compilation error. data during the interaction with
the program.
4.1 Exception Handling in Java –Types of Exceptions
try
{
-------
-------
}
catch(------)
{
-------
-------
}
4.1 try & catch Statement
Consider following example:
4.1 try & catch Statement
4.1 try & catch Statement
class demo
{
public static void main(String[] args)
{
try
{
int a = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException => " +
e.getMessage());
}
}
}
Output:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
class demo
{
public static void main(String args[])
{ catch(Exception e)
try {
{ System.out.println(“Index 5 out of bounds
try for length 5");
{ }
System.out.println("going to divide"); System.out.println("normal flow..");
int b =39/0; }
} }
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[5];
a[5]=14;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
4.1 Multiple catch Blocks
try catch(------)
{ {
------- -------
------- -------
} }
catch(------) catch(-----)
{ {
------- -------
------- -------
} }
4.1 Multiple catch Blocks
public class demo
{
public static void main(String[] args)
{
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");
}
}
}
4.1 finally statement
try catch(------)
{ {
------- -------
------- -------
} }
catch(------) finally
{ {
------- -------
------- -------
} }
class Division
{
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try Finally Statement -
{
result = a / (b - c); Example
System.out.println("result" + result);
}
catch (ArithmeticException e)
{
System.out.println(“Divide by 0 is not possible.");
}
finally
{
System.out.println("I am in final block");
}
}
}
4.1 throw Statement
The Java throw keyword is used to explicitly throw an
exception.
We can throw either checked or uncheked exception in java by
throw keyword.
The throw keyword is mainly used to throw custom exception.
Syntax:
throw new exception(“Some message”);
Example:
throw new ArithmeticException(“Error Message”);
throw new NumberFormatException(“Error
Message”);
throw new IOException(“Error Message”);
4.1 throw Statement - Example
public class MyClass
{
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args)
{
checkAge(15); // Set age to 15 (which is below 18...)
}
}
4.1 throws Statement
The throws keyword indicates what exception type may be
thrown by a method.
Syntax:
return_type method_name() throws exception
{
//method code
}
Or
return_type method_name() throws exception1,exception2
{
//method code
}
4.1 throws Statement - Example
public class demo
{
static void divide() throws ArithmeticException
{
int x=5, y=0, z;
z=x/y;
}
public static void main(String[] args)
{
try
{
divide();
}
catch(ArithmeticException e)
{
System.out.println(“Caught the exception” +e);
}
}
}
Built-in Exceptions in Java
Java defines several exception classes inside the standard
package java.lang.
Sr.No. Exception & Description Unchecked
ArithmeticException Exceptions
1
Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException
2
Array index is out-of-bounds.
ArrayStoreException
3
Assignment to an array element of an incompatible type.
ClassCastException
4
Invalid cast.
IllegalArgumentException
5
Illegal argument used to invoke a method.
IllegalMonitorStateException
6
Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException
7
Environment or application is in incorrect state.
Sr.No. Exception & Description
IllegalThreadStateException
8
Requested operation not compatible with the current thread state.
IndexOutOfBoundsException
9
Some type of index is out-of-bounds.
NegativeArraySizeException
10
Array created with a negative size.
NullPointerException
11
Invalid use of a null reference.
NumberFormatException
12
Invalid conversion of a string to a numeric format.
SecurityException
13
Attempt to violate security.
StringIndexOutOfBounds
14
Attempt to index outside the bounds of a string.
UnsupportedOperationException
15
An unsupported operation was encountered.
Sr.No. Exception & Description
ClassNotFoundException
1
Class not found.
CloneNotSupportedException
2 Attempt to clone an object that does not implement the Cloneable
interface.
IllegalAccessException
3
Access to a class is denied.
InstantiationException
4
Attempt to create an object of an abstract class or interface.
InterruptedException
5
One thread has been interrupted by another thread.
NoSuchFieldException
6
A requested field does not exist.
NoSuchMethodException
7
A requested method does not exist.
Checked
Exceptions
4.1 Chained Exception in Java
This feature allow you to relate one exception with another
exception, i.e one exception describes cause of another
exception.
For example, consider a situation in which a method throws
an ArithmeticException because of an attempt to divide by
zero but the actual cause of exception was an I/O error which
caused the divisor to be zero.
The method will throw only ArithmeticException to the
caller.
So the caller would not come to know about the actual cause
of exception.
Chained Exception is used in such type of situations.
4.1 Chained Exception in Java
java.lang.ArithmeticException : Exception
java.io.IOException : This is actual cause….
2.1 User-defined Custom Exception in Java
Java provides us facility to create our own exceptions
which are basically derived classes of Exception.
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
}
else {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");