Lecture-29 Java SE (Exception Handling-3)
Lecture-29 Java SE (Exception Handling-3)
Lecture-8
Today’s Agenda
01 Creating programmer defined exception\Custom
exception
05
Programmer defined\Customized Exceptions
• Many times, in some situations a programmer might not find any predefined exception
class to be used with throw.
For example, in case of a banking application the method withdraw has some minimum
limit like 500 else an exception will generate. In this case there is no predefined java’s
exception class.
• So, Java advises us to design our own exception classes.Such classes are called
customized exception class.
1. Inherit or extend any of the predefined exception class in our own exception class.
• The customized exceptions become checked exception if we inherit the base class
Exception.
• Since, only RuntimeException and its child classes are unchecked in nature, so
programmer has to specifically inherit anyone of those to create and unchecked
exception class.
Using the keyword “finally”
• There are certain statements in our program whose execution is so crucial that before
our program gets terminated, these statements must be executed.
• Example, if we have opened a file or any database connection and before the program
completes its execution the file or database connection should be closed.
• In such cases java suggests us to write such statements in a block whose execution is
guaranteed by java and such blocks are created using the keyword finally.
Using the keyword “finally”
• If no exception occurs finally block is executed.
• If an exception occurs inside the try block and its catch hasbeen defined, in such case
also finally is executed.
• Even if no catch block is used then also the finally block is executed.
• Moreover, a try block is required for an finally block. If an exception occurs outside try
block in that case finally block is not executed and also when the method System.exit()
is used.
Syntax
try
try
{
{
---
---
---
}
}
catch( ---)
finally
----
{
}
----
finally
----
----
}
}
}
Example
import java.util.*;
class TestFinally
{
public static void main(String [] args)
{
Scanner kb=new Scanner(System.in);
System.out.println(“Enter two numbers”);
try
{
int a=kb.nextInt();
int b=kb.nextInt();
int c=a/b;
System.out.println(“Division is ”+c);
}
Example
catch(ArithmeticException ex)
{
System.out.println(“Denominator should not be 0”);
}
finally
{
System.out.println(“Thank you! Have a good day”);
}
}
Multi catch feature
• We can use a single catch to handle multiple exceptions.
• Syntax :-
catch(ArithmeticException | InvalidNumeratorException ex)
{
System.out.println(ex.getMessage);
}
Thank you