2. 2
• An exception is an abnormal condition that arises in
a code sequence at run-time(run-time error)
• A Java exception is an object that describes an
exceptional (that is, error) condition that has
occurred in a piece of code
• When an exceptional condition arises, an object
representing that exception is created and thrown in
the method that caused the error
• The exception is caught and processed
3. 3
• Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally
• Program statements that you want to monitor for
exceptions are contained within a try block
• If an exception occurs within the try block, it is
thrown
• Your code can catch this exception (using catch) and
handle it
4. 4
• System-generated exceptions are automatically
thrown by the Java run-time system
• To manually throw an exception, use the keyword
throw
• Any exception that is thrown out of a method must
be specified as such by a throws clause
• Any code that absolutely must be executed before a
method returns is put in a finally block
5. 5
• This is the general form of an exception-handling
block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1 }
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2 }
// ...
finally {
// block of code to be executed before try block ends }
6. 6
Exception Types
• All exception types are subclasses of the built-in class
Throwable
• Immediately below Throwable are two subclasses
that partition exceptions into two distinct branches
• One branch is headed by Exception
• This class is used for exceptional conditions that user
programs should catch
7.
8. 8
• There is an important subclass of Exception, called
RuntimeException
• Exceptions of this type are automatically defined for
the programs that you write and include things such
as division by zero and invalid array indexing
9. 9
• The other branch is topped by Error, which defines
exceptions that are not expected to be caught under
normal circumstances by your program
• Exceptions of type Error are used by the Java run-
time system to indicate errors having to do with the
run-time environment, itself
• Stack overflow is an example of such an error
10. Uncaught Exceptions
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d; } //end of main } //end of cass
• Java run-time constructs a new exception object and
then throws this exception. This causes the execution of
Exc0 to stop, because once an exception has been
thrown, it must be caught by an exception handler and
dealt with immediately.
• The default handler displays a string describing the
exception, prints a stack trace from the point at which
the exception occurred, and terminates the program.
11. • Output: java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
class Exc1 { //method separated from main()
static void subroutine() {
int d = 0;
int a = 10 / d; }
public static void main(String args[]) {
Exc1.subroutine(); } }
• The resulting stack trace from the default exception
handler shows how the entire call stack is displayed:
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:6)
12. 12
Using try and catch:
• Handling an exception manually provides two
benefits
• First, it allows you to fix the error
• Second, it prevents the program from automatically
terminating
• To guard against and handle a run-time error, simply
enclose the code that you want to monitor inside a
try block.
• Immediately following the try block, include a catch
clause that specifies the exception type that you wish
to catch.
13. 13
class Exc2 {
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."); } }
This program generates the following output:
Division by zero.
After catch statement.
14. Example 2: ArrayIndexOutOfBounds Exception
Class: Java.lang.ArrayIndexOutOfBoundsException
This is a built in class present in java.lang package. This exception occurs
when the referenced element does not exist in the array. For e.g. If
array is having only 5 elements and we are trying to display 7th element
then it would throw this exception.
15. class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Output:
ArrayIndexOutOfBounds
16. Example 3: StringIndexOutOfBound Exception
Class: Java.lang.StringIndexOutOfBoundsException
An object of this class gets created whenever an index is
invoked of a string, which is not in the range.
Each character of a string object is stored in a particular index
starting from 0.
To get a character present in a particular index of a string we
can use a method charAt(int) of java.lang.String where int
argument is the index.
17. E.g.
class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="easysteps2buildwebsite";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output:
StringIndexOutOfBoundsException!!
Exception occurred because the referenced index was not present in the
String.
18. Multiple catch blocks in Java
1. A try block can have any number of catch blocks.
2. A catch block that is written for catching the class Exception can catch all other
exceptions
Syntax:
catch(Exception e){
//This catch block catches all the exceptions
}
3. If multiple catch blocks are present in a program then the above mentioned catch
block should be placed at the last as per the exception handling best practices.
4. If the try block is not throwing any exception, the catch block will be completely
ignored and the program continues.
5. If the try block throws an exception, the appropriate catch block (if one exists) will
catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
6. All the statements in the catch block will be executed and then the program continues.
19. 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...
20. Types of exceptions
1. Checked exceptions
• All exceptions other than Runtime Exceptions are known as Checked
exceptions as the compiler checks them during compilation to see whether the
programmer has handled them or not.
• If these exceptions are not handled/declared in the program, it will give compilation
error.
Examples of Checked Exceptions :-
ClassNotFoundException,
IllegalAccessException
IOException
EOFException etc.
21. 2.Unchecked Exceptions
• Runtime Exceptions are also known as Unchecked Exceptions as the compiler do
not check whether the programmer has handled them or not but it’s the duty of the
programmer to handle these exceptions and provide a safe exit.
• These exceptions need not be included in any method’s throws list because
compiler does not check to see if a method handles or throws these exceptions.
Examples of Unchecked Exceptions:-
ArithmeticException,
ArrayIndexOutOfBoundsException,
NullPointerException
etc.
22. Why to handle exception?
If an exception is raised, which has not been handled by programmer then
program execution can get terminated and system prints a non user friendly error
message.
Ex:-Take a look at the below system generated exception
An exception generated by the system is given below
Exception in thread "main" java.lang.ArithmeticException: / by zero at
ExceptionDemo.main(ExceptionDemo.java:5)
[ExceptionDemo : The class name main : The method name
ExceptionDemo.java : The filename java:5 : Line number]
23. What is Finally Block
1. A finally statement must be associated with a try statement. It identifies a block of
statements that needs to be executed regardless of whether or not an exception
occurs within the try block.
2. After all other try-catch processing is complete, the code inside the finally block
executes. It is not mandatory to include a finally block at all, but if you do, it will run
regardless of whether an exception was thrown and handled by the try and catch parts
of the block.
3. In normal execution the finally block is executed after try block. When any exception
occurs first the catch block is executed and then finally block is executed.
4. An exception in the finally block, exactly behaves like any other exception.
5. The code present in the finally block executes even if the try or catch block contains
control transfer statements like return, break or continue
24. Syntax of Finally block
try
{
//statements that may cause an
exception
}
finally
{
//statements to be executed
}
25. Example: Finally Block
Example 1: Below example illustrates finally block when no exception occurs in try
block
class Example1{
public static void main(String args[]){
try{
System.out.println("First statement of try block ");
int num=45/3;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block 15
finally block
Out of try-catch-finally block
26. Example 2:Below example illustrates finally block execution when exception occurs
in try block but doesn’t get handled in catch block.
class Example2{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block
finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Example2.main(Details.java:6)
27. Example 3:Below example illustrates execution of finally, when exception occurs in
try block and handled in catch block.
class Example3{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("ArithmeticException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block
ArithmeticException
finally block
Out of try-catch-finally block
28. Throw vs Throws in java
1. Throws clause in used to declare an exception and throw keyword is used to throw
an exception explicitly.
2. If we see syntax wise, throw is followed by an instance variable and throws is
followed by exception class names.
3. The keyword throw is used inside method body to invoke an exception and throws
clause is used in method declaration (signature).
for e.g.
Throw:
....
static{
try {
throw new Exception("Something went wrong!!");
} catch (Exception exp) {
System.out.println("Error: "+exp());
}
}
29. Throws:
public void sample() throws ArithmeticException{
//Statements
.....
//if (Condition : There is an error)
ArithmeticException exp = new ArithmeticException();
throw exp;
...
}
4. By using Throw keyword in java you cannot throw more than one exception but
using throws you can declare multiple exceptions..
for e.g.
Throw:
throw new ArithmeticException("An integer should not be divided by zero!!")
throw new IOException("Connection failed!!")
Throws:
throws IOException, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException
30. How to throw exception in java with example
(i) In terms of already defined exceptions
(ii) In terms of user defined exceptions
(i) In java we have already defined exception classes such as ArithmeticException,
ArrayIndexOutOfBoundsException, NullPointerException etc. There are certain
conditions defined for these exceptions and on the occurrence of those conditions
they are implicitly thrown by JVM(java virtual machine).
(ii) Do you know that a programmer can create a new exception and throw it
explicitly?
• These exceptions are known as user-defined exceptions. In order to throw user
defined exceptions, throw keyword is being used.
• You can also throw an already defined exception like ArithmeticException,
IOException etc.
31. How to throw user defined exception in java with example
Example1: How to throw user defined exception using throw keyword
class MyOwnException extends Exception {
public MyOwnException(String msg){
super(msg);
}}
class EmployeeTest {
static void employeeAge(int age) throws MyOwnException{
if(age < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args) {
try {
employeeAge(-2);
}
catch (MyOwnException e) {
System.out.println(e);
}
}
}
Output:
MyOwnException: Age can't be less than zero
32. How to throw already defined exception in java with example
Example2: How to throw an already defined exception using throw keyword
class Exception2{
static int sum(int num1, int num2){
if (num1 == 0)
throw new ArithmeticException("First parameter is not valid");
else
System.out.println("Both parameters are correct!!");
return num1+num2;
}
public static void main(String args[]){
int res=sum(0,12);
System.out.println(res);
System.out.println("Continue Next statements");
}
}
Output:
Exception in thread main java.lang.ArithmeticException: First parameter is
not valid
33. Throws Keyword Example in Java
Exception Handling
As we know that there are two types of exception – checked and
unchecked. Checked exceptions (compile time) are the one which forces
the programmer to handle it, without which the program doesn’t compile
successfully. While unchecked exception (Runtime) doesn’t get checked
during compilation. “Throws keyword” is mainly used for handling
checked exception as using throws we can declare multiple exceptions in
one go. Let’s understand this with the help of an example.
34. Example of throws Keyword
import java.io.*;
public class ThrowExample {
void mymethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("Exception Message1");
else
throw new ClassNotFoundException("Exception Message2");
}
}
class Demo{
public static void main(String args[]){
try{
ThrowExample obj=new ThrowExample();
obj.mymethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output:
java.io.IOException: Exception Message1
35. 35
// This program contains error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[ ]) {
throwOne(); }
}
• To make this to compile-
• you need to declare that throwOne( ) throws
IllegalAccessException.
• main( ) must define a try/catch statement that catches
this exception.
36. 36
class ThrowsDemo {
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); } } }
Here is the output generated by running this program:
inside throwOne
caught java.lang.IllegalAccessException: demo
Editor's Notes
Exception handling fundamentals, types of exceptions, example code which monitors and handles exception, user-defined exception
In simple terms, a stack trace is a list of the method calls that the application was in the middle of when an Exception was thrown.
IllegalAccess: trying to access private member outside, accessing static member in a normal method etc.
IOException: file not found or reading beyond file size
Attempt to access the value of an object assigned with NULL
**
*
*public String toString(){//overriding the toString() method Â
  return rollno+" "+name+" "+city; Â
 } Â