0% found this document useful (0 votes)
73 views10 pages

Public Class Closeresource (Public Static Void Main (String Args) (Try (

The try-with-resources statement automatically closes resources, replacing the finally block. It handles both normal and abrupt completion of the try statement. The BufferedReader class implements AutoCloseable in Java 7, allowing its instance to be automatically closed in a try-with-resources statement. Multiple resources can be closed by separating them with semicolons. Exceptions must be handled specifically in the catch blocks based on class hierarchy. Custom exceptions can be created by extending existing exception classes like Throwable, Exception, RuntimeException. Exceptions can be rethrown from catch blocks by throwing the caught exception.

Uploaded by

Kuldeep Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
73 views10 pages

Public Class Closeresource (Public Static Void Main (String Args) (Try (

The try-with-resources statement automatically closes resources, replacing the finally block. It handles both normal and abrupt completion of the try statement. The BufferedReader class implements AutoCloseable in Java 7, allowing its instance to be automatically closed in a try-with-resources statement. Multiple resources can be closed by separating them with semicolons. Exceptions must be handled specifically in the catch blocks based on class hierarchy. Custom exceptions can be created by extending existing exception classes like Throwable, Exception, RuntimeException. Exceptions can be rethrown from catch blocks by throwing the caught exception.

Uploaded by

Kuldeep Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 10

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether

the try statement completes normally or abruptly. The following example uses a finally block instead
of a try-with-resources statement:
public class CloseResource{
public static void main(String[] args) {
BufferedReader br=null;
try {
br = new BufferedReader(new FileReader("D:/f1.txt"));
System.out.println(br.readLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();}}}}
The class BufferedReader, in Java SE 7 and later, implements the interface
java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-
resource statement, it will be closed regardless of whether the try statement completes
normally or abruptly (as a result of the method BufferedReader.readLine throwing an
IOException).
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CloseResourceWithJava7{


public static void main(String[] args) {
try (BufferedReader br =
new BufferedReader(new FileReader("D:/f1.txt"))) {
System.out.println(br.readLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();}}}
Close Multiple Resources:-
try (Resource1;Resource2) {}

Multiple catch with Class hierarchy:-


public class MultipleCatch{
public static void main(String[] args) {
try (BufferedReader br =
new BufferedReader(new FileReader("D:/f1.txt"))) {
System.out.println(br.readLine());
} catch (Exception e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();}}} // compiler error:- unreachable catch block.

Multiple catch with Java7:-


public class MultipleExceptionWithJava7{
public static void main(String[] args) {
try (BufferedReader br =
new BufferedReader(new FileReader("D:/f1.txt"))) {
System.out.println(br.readLine());
} catch(IOException | NullPointerException ex){
ex.printStackTrace();
} }} Note:- ex is final can not reassign.
public class UnreachableException{
public static void main(String[] args) {
try (BufferedReader br =
new BufferedReader(new FileReader("D:/f1.txt"))) {
System.out.println(br.readLine());
} catch(IOException | SQLException | NullPointerException ex){
ex.printStackTrace();
} }}
Compiler error:-Unreachable catch block for SQLException. This exception is never thrown
from the try statement body.

public class Check{


public static void main(String[] args) {
try (BufferedReader br =
new BufferedReader(new FileReader("D:/f1.txt"))) {
System.out.println(br.readLine());
} catch(IOException | Exception ex){
ex.printStackTrace();
} }}

Or catch(Exception | IOException ex)


Creating Custom Exception Classes:-
We can create our custom exception with the following:-
 Extending the Throwble class. (It will be checked exception)
 Extending the Error class.(It will be unchecked exception)
 Extending the Exception class.(It will be checked exception)
 Extending the RuntimeException class.(It will be unchecked exception)
 Extending any Throwble’s hierarchy class.

public class CustomExceptionDemo{


public static void main(String[] args) {
doStuff();
}
static void doStuff() {
throw new MyException(); // Throw a checked exception
}
}
class MyException extends Exception { }
Rethrowing the Same Exception:-
You can throw a new exception from a catch clause, you can also throw the same exception you just
caught.
If you throw a checked exception from a catch clause, you must also declare that exception! In other
words, you must handle or declare.
public class RethrowExDemo{
public static void main(String[] args) {
try (BufferedReader br =
new BufferedReader(new FileReader("D:/f1.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
throw e;} }} // Compiler error. To solve handle it within catch block or throws it.

Let's define two broad categories of exceptions and errors:


■ JVM exceptions Those exceptions or errors that are either exclusively
or most logically thrown by the JVM.
■ Programmatic exceptions Those exceptions that are thrown explicitly
by application and/or API programmers.
class JVMThrowExDemo {
static String s;
public static void main(String [] args) {
System.out.println(s.length());}}
The code will compile just fine, and the JVM will throw a NullPointerException when it tries to invoke
the length() method on null reference s.
Take a look at this code:
void go() { // recursion gone bad
go();
}
You'll get a StackOverflowError. Again, only the JVM knows when this moment occurs, and the JVM
will be the source of this error.
Programmatically Thrown Exceptions:- That are throwing explicitly by the programmer.
int parseInt(String s) throws NumberFormatException{}

ExceptionHandling with MethodOverriding


There are many rules if we talk about methodoverriding with exception handling. The
Rules are as follows:
If the superclass method does not declare an exception
If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but it can declare unchecked exception.
If the superclass method declares an exception
If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception, unchecked exception or no exception but cannot
declare parent exception.
1) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception.
import java.io.*;  
class Parent{  
  void msg(){System.out.println("parent");}  
}  
  
class Child extends Parent{  
  void msg()throws IOException{  
    System.out.println("child");  
  }  
  public static void main(String args[]){  
   Parent p=new Child();  
   p.msg();  
  }  
}  // Compiler error:- Exception IOException is not compatible with throws clause in Parent.msg().

Note:- But if we throws checked exception it will compile fine.


2) Rule: If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception, unchecked exception or no exception but cannot declare parent exception.
Parent and Child with same exception:-
public class Student extends Parent{
void msg()throws Exception{
System.out.println("child");
}
public static void main(String args[]){
}
}
class Parent{
void msg() throws Exception{System.out.println("parent");}
} // Fine
Parent and Child with subclass exception:-
public class Student extends Parent{
void msg()throws FileNotFoundException {
System.out.println("child");
}
public static void main(String args[]){
}
}
class Parent{
void msg() throws IOException{System.out.println("parent");}
} // Fine
Parent with checked and Child with unchecked exception:-
public class Student extends Parent{
void msg()throws ClassCastException {
System.out.println("child");
}
public static void main(String args[]){
}
}
class Parent{
void msg() throws ClassNotFoundException{System.out.println("parent");}
} // Fine

Child with parent and checked exception:-


public class Student extends Parent{
void msg()throws IOException {
System.out.println("child");
}
public static void main(String args[]){
}
}
class Parent{
void msg() throws IOException{System.out.println("parent");}
} // Compiler errr:-Exception IOException is not compatible with throws clause in Parent.msg()

You might also like