0% found this document useful (0 votes)
36 views

Exception Handling2

The document discusses different aspects of exception handling in Java, including: 1. Examples of multiple catch blocks that catch different specific exceptions as well as the generic Exception. 2. An example of a nested try block, where a try block is within another try block, allowing for nested exception handling. 3. Details on the finally block, which ensures code is always executed whether an exception occurs or not. Several examples are provided. 4. The throw keyword, which can be used to explicitly throw exceptions, and examples of checking conditions and throwing exceptions. 5. The throws clause, which is used to declare checked exceptions and handle them without try-catch, allowing exceptions to be propagated.

Uploaded by

Kousik manna
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Exception Handling2

The document discusses different aspects of exception handling in Java, including: 1. Examples of multiple catch blocks that catch different specific exceptions as well as the generic Exception. 2. An example of a nested try block, where a try block is within another try block, allowing for nested exception handling. 3. Details on the finally block, which ensures code is always executed whether an exception occurs or not. Several examples are provided. 4. The throw keyword, which can be used to explicitly throw exceptions, and examples of checking conditions and throwing exceptions. 5. The throws clause, which is used to declare checked exceptions and handle them without try-catch, allowing exceptions to be propagated.

Uploaded by

Kousik manna
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

EXCEPTION HANDLING

BY
TANUSREE SAHA
EXAMPLE MULTIPLE CATCH BLOCK:
 public class MB2 {

 public static void main(String[] args) {


 try{
 String s=null;
 System.out.println(s.length());
 }
 catch(ArithmeticException e)
 {
 System.out.println("Arithmetic Exception occurs");
 }
 catch(ArrayIndexOutOfBoundsException e)
 {
 System.out.println("ArrayIndexOutOfBounds Exception occurs");
 }
 catch(Exception e)
 {
 System.out.println("Parent Exception occurs");
 }
 System.out.println("rest of the code");
 }
 }
 HERE EXCEPTION IS BASICCALLY EXCEPTION ON Nullpointexception BUT NO CATCH BLOCK IS THERE TO
HANDEL IT SO IS HANDLED BY GENERIC CATCH
EXAMPLE MULTIPLE CATCH BLOCK:
 public class MB3 {

 public static void main(String[] args) {


 try{
 String s=null;
 System.out.println(s.length());
 }
 catch(NullPointerException e)
 {
 System.out.println("null point Exception occurs");
 }
 catch(ArithmeticException e)
 {
 System.out.println("Arithmetic Exception occurs");
 }
 catch(ArrayIndexOutOfBoundsException e)
 {
 System.out.println("ArrayIndexOutOfBounds Exception occurs");
 }
 catch(Exception e)
 {
 System.out.println("Parent Exception occurs");
 }
 System.out.println("rest of the code");
 }
 }
Java Nested try block

The try block within a try block is known as


nested try block in java.

 Why use nested try block:?


 Sometimes a situation may arise where a part

of a block may cause one error and the entire


block itself may cause another error. In such
cases, exception handlers have to be nested.
Syntax:

 ....
 try
 {
 statement 1;
 statement 2;
 try
 {
 statement 1;
 statement 2;
 }
 catch(Exception e)
 {
 }
 }
 catch(Exception e)
 {
 }
 ....
EXAMPLE: NESTED TRY
 class NTC1{
 public static void main(String args[]){
 try{
 try{
 System.out.println("going to divide");
 int b =39/0;
 }
 catch(ArithmeticException e)
 {
 System.out.println(e);
 }
 try{
 int a[]=new int[5];
 a[5]=4;
 }
 catch(ArrayIndexOutOfBoundsException e)
 {
 System.out.println(e);
 }

 System.out.println("other statement");
 }
 catch(Exception e)
 {
 System.out.println("handeled");
 }
 System.out.println("normal flow..");
 }
EXCEPTION HANDLING
BY
TANUSREE SAHA
Java Finally block – Exception handling

 A finally block contains all the crucial


statements that must be executed whether
exception occurs or not. The statements
present in this block will always execute
regardless of whether exception occurs in try
block or not such as closing a connection,
stream etc.
Block Diagram: Finally
SYNTAX: FINALLY
 try
 { //Statements that may cause an exception
 }
 catch
 { //Handling exception
 }
 finally
 { //Statements to be executed
 }
Simple example of Finally
 class FB1
 {
 public static void main(String args[]) {
 try{
 int num=121/0;
 System.out.println(num);
 }
 catch(ArithmeticException e){
 System.out.println("Number should not be divided by zero");
 }
 /* Finally block will always execute
 * even if there is no exception in try block
 */
 finally{
 System.out.println("This is finally block");
 }
 System.out.println("Out of try-catch-finally");
 }
 }
Usage of Java finally

 Case 1: Let's see the java finally example where exception doesn't
occur.

 class FB2{
 public static void main(String args[]){
 try{
 int data=25/5;
 System.out.println(data);
 }
 catch(NullPointerException e){System.out.println(e);}
 finally{System.out.println("finally block is always executed");}
 System.out.println("rest of the code...");
 }
 }
Usage of Java finally
 Case 2: Let's see the java finally example where exception
occurs and not handled.

 class FB3{
 public static void main(String args[]){
 try{
 int data=25/0;
 System.out.println(data);
 }
 catch(NullPointerException e){System.out.println(e);}
 finally{System.out.println("finally block is always executed");}
 System.out.println("rest of the code...");
 }
 }
Usage of Java finally
 Case 3: Let's see the java finally example where exception
occurs and handled.
 public class FB4{
 public static void main(String args[]){
 try{
 int data=25/0;
 System.out.println(data);
 }
 catch(ArithmeticException e){System.out.println(e);}
 finally{System.out.println("finally block is always executed");}
 System.out.println("rest of the code...");
 }
 }
Few Important points regarding finally block

 1. A finally block must be associated with a try block, you cannot


use finally without a try block. You should place those statements
in this block that must be executed always.
 2. Finally block is optional, as we have seen in previous tutorials
that a try-catch block is sufficient for exception handling, however
if you place a finally block then it will always run after the
execution of try block.
 3. In normal case when there is no exception in try block then the
finally block is executed after try block. However if an exception
occurs then the catch block is executed before finally block.
 4. An exception in the finally block, behaves exactly like any other
exception.
 5. The statements present in the finally block execute even if the
try block contains control transfer statements like return, break or
continue.
Another example of finally block and return statement

 class FIR
 {
 public static void main(String args[])
 {
 System.out.println(FIR.myMethod());
 }
 public static int myMethod()
 {
 try {
 return 112;
 }

 finally {
 System.out.println("This is Finally block");
 System.out.println("Finally block ran even after return statement");
 }
 }
 }
Throw & Throws
EXCEPTION HANDLING
BY
TANUSREE SAHA
Java throw exception

 In Java we have already defined exception classes such as


ArithmeticException, NullPointerException, ArrayIndexOutOfBounds
exception etc. These exceptions are set to trigger on different-2
conditions. For example when we divide a number by zero, this
triggers ArithmeticException, when we try to access the array element
out of its bounds then we get ArrayIndexOutOfBoundsException.
 We can define our own set of conditions or rules and throw an
exception explicitly using throw keyword. For example, we can throw
ArithmeticException when we divide number by 5, or any other
numbers, what we need to do is just set the condition and throw any
exception using throw keyword. Throw keyword can also be used for
throwing custom exceptions
 We can throw either checked or unchecked exception in java by
throw keyword
SYNTAX: THROW EXCEPTION
throw new exception_class("error message");
OR
throw new IOException("sorry device error);
EXAMPLE: THROW
 public class TE1{
 static void validate(int age){
 if(age<18)
 throw new ArithmeticException("not valid");
 else
 System.out.println("welcome to vote");
 }
 public static void main(String args[]){
 validate(16);
 System.out.println("rest of the code...");
 }
 }
Another example
 public class TE2 {
 static void checkEligibilty(int stuage, int stuweight){
 if(stuage<12 && stuweight<40) {
 throw new ArithmeticException("Student is not eligible for
registration");
 }
 else {
 System.out.println("Student Entry is Valid!!");
 }
 }

 public static void main(String args[]){


 System.out.println("Welcome to the Registration process!!");
 checkEligibilty(20, 59);
 System.out.println("Have a nice day..");
 }
 }
Throws clause in java – Exception handling

 As we know that there are two types of


exception checked and unchecked. Checked
exception (compile time) force you to handle
them, if you don’t handle them then the
program will not compile.
On the other hand unchecked exception
(Runtime) doesn’t get checked during
compilation.
 Throws keyword is used for handling checked

exceptions . By using throws we can declare


multiple exceptions in one go.
What is the need of having throws keyword
when you can handle exception using try-
catch?
 We already know we can handle exceptions using try-catch
block.
The throws does the same thing that try-catch does but there are
some cases where you would prefer throws over try-catch. For
example:
Lets say we have a method myMethod() that has statements that
can throw either ArithmeticException or NullPointerException, in
this case you can use try-catch as shown below:
 public void myMethod() { try { // Statements that
might throw an exception } catch
(ArithmeticException e) { // Exception handling
statements } catch (NullPointerException e) { //
Exception handling statements } }
NEED
 suppose you have several such methods that can cause
exceptions, in that case it would be tedious to write these
try-catch for each method. The code will become
unnecessary long and will be less-readable.
One way to overcome this problem is by using throws like
this: declare the exceptions in the method signature using
throws and handle the exceptions where you are calling
this method by using try-catch.

Another advantage of using this approach is that you will


be forced to handle the exception when you call this
method, all the exceptions that are declared using throws,
must be handled where you are calling this method else
you will get compilation error.
SYNTAX: THROWS
 public void myMethod() throws
ArithmeticException, NullPointerException { //
Statements that might throw an exception }
 public static void main(String args[])
 { try
 { myMethod();
 }
 catch (ArithmeticException e) { // Exception
handling statements }
 catch (NullPointerException e) { // Exception
handling statements } }
Example: Throws
 import java.io.*;
 class TSE {
 void myMethod(int num)throws IOException, ClassNotFoundException{
 if(num==1)
 throw new IOException("IOException Occurred");
 else
 throw new ClassNotFoundException("ClassNotFoundException");
 }
 }

 public class TSE1{


 public static void main(String args[]){
 try{
 TSE obj=new TSE();
 obj.myMethod(1);
 }catch(Exception ex){
 System.out.println(ex);
 }
 }
 }
1.There are two cases:Case1:You caught the exception i.e. handle the
exception using try/catch.
2.Case2:You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception


•In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.
Case1: You handle the exception
 import java.io.*;
 class M{
 void method()throws IOException{
 throw new IOException("device error");
 }
 }
 public class Testthrows2{
 public static void main(String args[]){
 try{
 M m=new M();
 m.method();
 }catch(Exception e){System.out.println("exception handled");}

 System.out.println("normal flow...");
 }
 }
Case2: You declare the exception

 A)In case you declare the exception, if


exception does not occur, the code will be
executed fine.
 B)In case you declare the exception if

exception occures, an exception will be


thrown at runtime because throws does not
handle the exception.
A)Program if exception does not
occur
 import java.io.*;
 class M{
 void method()throws IOException{
 System.out.println("device operation performed");
 }
 }
 class Testthrows3{
 public static void main(String args[])throws IOException{//
declare exception
 M m=new M();
 m.method();

 System.out.println("normal flow...");
 }
 }
B)Program if exception occurs
 import java.io.*;
 class M{
 void method()throws IOException{
 throw new IOException("device error");
 }
 }
 class Testthrows4{
 public static void main(String args[])throws IOException{//
declare exception
 M m=new M();
 m.method();

 System.out.println("normal flow...");
 }
 }
Difference between throw and throws in Java

throw throws

Java throw keyword is used to Java throws keyword is used to


explicitly throw an exception. declare an exception
Checked exception cannot be Checked exception can be
propagated using throw only. propagated with throws.
Throw is followed by an instance. Throws is followed by class
Throw is used within the method. Throws is used with the method
signature
You cannot throw multiple You can declare multiple
exceptions. exceptions e.g.
public void method()throws
IOException,SQLException.
throw new throws ArithmeticException,
ArithmeticException("Arithmetic IOException,SQLException;
Exception");
Example
 Throw Example
 public class Example1{ void checkAge(int age){ if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else System.out.println("Eligible for voting"); } public static
void main(String args[]){ Example1 obj = new Example1();
obj.checkAge(13); System.out.println("End Of Program"); } }
 Throws Example
 public class Example1{ int division(int a, int b) throws
ArithmeticException{ int t = a/b; return t; } public static
void main(String args[]){ Example1 obj = new Example1();
try{ System.out.println(obj.division(15,0)); }
catch(ArithmeticException e){ System.out.println("You
shouldn't divide number by zero"); } } }
Difference between final, finally and finalize

final finally finalize


Final is used to apply Finally is used to place Finalize is used to perform clean
restrictions on class, method important code, it will be up processing just before object
and variable. Final class can't be executed whether exception is is garbage collected.
inherited, final method can't be handled or not.
overridden and final variable
value can't be changed.
Final is a keyword. Finally is a block. Finalize is a method.

class FinalExample{ class FinallyExample{ class FinalizeExample{


public static void main(String[] public static void main(String[] public void finalize()
args){ args){ {System.out.println("finalize calle
final int x=100; try{ d");}
x=200;//Compile Time Error int x=300; public static void main(String[]
}} }catch(Exception e) args){
{System.out.println(e);} FinalizeExample f1=new Finaliz
finally{System.out.println("finally eExample();
block is executed");} FinalizeExample f2=new Finaliz
}} eExample();
f1=null;
f2=null;
System.gc();
}}
User defined exception in java

 In java we have already defined, exception classes such


as ArithmeticException, NullPointerException etc. These
exceptions are already set to trigger on pre-defined
conditions such as when you divide a number by zero it
triggers ArithmeticException, In the last tutorial we
learnt how to throw these exceptions explicitly based
on your conditions using throw keyword.
 In java we can create our own exception class and throw
that exception using throw keyword. These exceptions
are known as user-defined or custom exceptions. In
this tutorial we will see how to create your own custom
exception and throw it on a particular condition.
Example of User defined exception in Java

 class MyException extends Exception{


 String str1;
 /* Constructor of custom exception class
 * here I am copying the message that we are passing while
 * throwing the exception to a string and then displaying
 * that string along with the message.
 */
 MyException(String str2) {
 str1=str2;
 }
 public String toString(){
 return ("MyException Occurred: "+str1) ;
 }
 }

 class UDE1{
 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) ;
 }
 }
 }
Another Example of Custom Exception
 class InvalidProductException extends Exception
 {
 public InvalidProductException(String s)
 {
 // Call constructor of parent Exception
 super(s);
 }
 }

 public class UDE2
 {
 void productCheck(int weight) throws InvalidProductException{
 if(weight<100){
 throw new InvalidProductException("Product Invalid");
 }
 }

 public static void main(String args[])
 {
 UDE2 obj = new UDE2();
 try
 {
 obj.productCheck(60);
 }
 catch (InvalidProductException ex)
 {
 System.out.println("Caught the exception");
 System.out.println(ex.getMessage());
 }
 }
 }
 Output:
assignment
 Write java program o following:
 Arithmetic exception
 ArrayIndexOutOfBounds Exception
 NumberFormat Exception
 StringIndexOutOfBound Exception
 NullPointer Exception
Thank You

You might also like