Showing posts with label checked exception. Show all posts
Showing posts with label checked exception. Show all posts

Tuesday, 29 January 2019

Groovy: Method vs checked exceptions


In Groovy, you can treat checked exceptions like unchecked exceptions.

For example, in Java, you need to either catch or throw the checked exception from the method. In Groovy, you need not do either of these.

For example, below snippet read the contents of a file line-by-line.
public void readFile(String filePath) throws IOException {
       BufferedReader br = new BufferedReader(new FileReader(filePath));
       String line = br.readLine();
       while (line != null) {
              System.out.println(line);
              line = br.readLine();
       }
       br.close();
}

As you see the snippet, I am throwing IOException from the method readFile. But it is not the case in Groovy, you can avoid of throwing IOException.

HelloWorld.groovy
public void readFile(String filePath){
 BufferedReader br = new BufferedReader(new FileReader(filePath));
 String line = br.readLine();
 while (line != null) {
  System.out.println(line);
  line = br.readLine();
 }
 br.close();
}

readFile("C:\\Users\\Krishna\\Downloads\\version.txt")


Previous                                                 Next                                                 Home

Thursday, 27 February 2014

checked vs unchecked Exceptions

1. Checked exceptions are those which are checked at compile time, Unchecked exceptions are not checked at compile time and raised at run time.

2. In Java, Error, RuntimeExceptions and its subclasses comes under unchecked exceptions category, where as Exception and its sub classes comes under checked exceptions category.

3. Checked exceptions are subject to catch/specify requirement.

For Example, see the below program,

import java.io.*;

class CheckedEx{
 public static void main(String args[]){
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter your name ");
  String name = br.readLine();
  System.out.println("Hi " + name);
 }
}
   
br.readLine(), throws IOException, which is a checked exception, so compiler checks whether the program handles it or not, If the program is not handling then compiler throws the error. Above program is not handling the cecked Exception (IOException), so compiler throws the below error.

CheckedEx.java:7: error: unreported exception IOException; must be caught or declared to be thrown
String name = br.readLine();
^
1 error

To make the program compile and runs fine, There are two options

Option 1: program can handle the IOException.
import java.io.*;

class CheckedEx{
 public static void main(String args[]){
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  try{
   System.out.println("Enter your name ");
   String name = br.readLine();
   System.out.println("Hi " + name);
  }
  catch(IOException e){
   System.out.println(e);
  }
 }
}

Output
Enter your name
abc
Hi abc

Option 2: program can throws the IOException.
import java.io.*;

class CheckedEx{
 public static void main(String args[]) throws IOException{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter your name ");
  String name = br.readLine();
  System.out.println("Hi " + name);
 }
}

Output
Enter your name
abc
Hi abc

4. Program can handle and recover from checked exceptions, Of course from RuntimeException recovery is possible. Error are special category of unchecked exception, Where recovery from them is almost impossible.

5. Compiler throws an error, if the program tries to handle a checked exception, which will never occurs in the program.

import java.io.*;

class CheckedEx{
 public static void main(String args[]){
  try{
   int a = 10+20;
  }
  catch(IOException e){
  
  }
 }
}

When you tries to compile the above program, compiler throws the below error

CheckedEx.java:7: error: exception IOException is never thrown in body of corresponding try statement
catch(IOException e){
^
1 error

Custom Exceptions                                                 Overriding vs Exception Handling                                                 Home

Tuesday, 25 February 2014

Throwable class

Throwable is the super class for all the errors and Exceptions.

Only the objects of Throwable and its subclasses can be thrown by JVM or throw statement. Catch can able to catch any object which is a sub class of Throwable. So we can catch errors and RuntimeExceptions also.

The classes RuntimeException, Error and its subclasses are called as unchecked exceptions, since these are not checked at compile time. All other classes including Throwable are called checked Exceptions, since these are checked at compile time.

Checked Exceptions must be thrown or handled in the program, other wise program won't compile.

class CheckedEx extends Throwable{
 CheckedEx(String s){
  super(s);
 }

 CheckedEx(){

 }

 void print()throws CheckedEx{
  throw new CheckedEx("I am checked Exception");
 }
}
   
CheckedEx extending the class Throwable, So it is a checked exception. So it must be handled or thrown.

class ThrowableEx{
 public static void main(String args[]){
  CheckedEx obj = new CheckedEx();
  obj.print();
 }
}
   
When you tries to compile the above prgram, compiler thrws below error. Since checked exception is not handled or thrown.

ThrowableEx.java:4: error: unreported exception CheckedEx; must be caught or declared to be thrown
obj.print();
^
1 error

To make the program compiles fine, we have two options.

Option 1 : Throw the exception
class ThrowableEx{
 public static void main(String args[])throws Throwable{
  CheckedEx obj = new CheckedEx();
  obj.print();
 }
}


Output
Exception in thread "main" CheckedEx: I am checked Exception
 at CheckedEx.print(CheckedEx.java:12)
 at ThrowableEx.main(ThrowableEx.java:4)
 
Option 2: Handle the exception using catch
class ThrowableEx{
 public static void main(String args[]){
  CheckedEx obj = new CheckedEx();
  try{
   obj.print();
  }
  catch(CheckedEx e){
   System.out.println("Exception occured " + e);
  }
 }
}


Output
 Exception occured CheckedEx: I am checked Exception


A Throwable object contains the information about the stack trace, at the time it was created.

Example
class ThrowableEx{
 public static void main(String args[]){
  CheckedEx obj = new CheckedEx();
  try{
   obj.print();
  }
  catch(CheckedEx e){
   System.out.println("Stack trace is ");
   e.printStackTrace(System.out);
  }
 }
}
   
Output
Stack trace is
CheckedEx: I am checked Exception
 at CheckedEx.print(CheckedEx.java:12)
 at ThrowableEx.main(ThrowableEx.java:5)
    


error vs exception                                                 Throwable constructors                                                 Home

Difference between Error Vs Exception

1. Error are abnormal situations where program can't handle those, where as Exception is also a abnormal situation, but program handle the exception.

2. Error, RuntimeExceptions and its subclasses comes under uncheckedexceptions category, where as Exception and its sub classes comes under checked exceptions category.

3. Almost in all the cases, program is not recoverable from an error,
Ex: OutOfMemoryError, StackOverflowError. But you can catch the exception and recover from that.

4. Both error and RuntimeException comes under unchecked exceptions category, program can handle RuntimeException, where as it can't handle error


Exception Hierarchy                                                 Throwable class                                                 Home

Monday, 24 February 2014

Difference between throw and throws

1. The key word throws is used in method declaration, this specify what kind of exception we may expect from this method. The key word throw is used to throw an object that is instance of class Throwable.

2. You can specify multiple exceptions thrown by a method using throws clause, where as throw throws one Throwable object only.

3. throw keyword can be used in switch statement, where as throws only in the method declaration.

Example
class ThrowEx{
 static void throwExceptions(int num){
  switch(num){
   case 1:
    throw new RuntimeException("Exception number 1");
   case 2:
    throw new RuntimeException("Exception number 2");
   case 3:
    throw new RuntimeException("Exception number 3");
   default:
    System.out.println("No Exceptions thrown");
  }
 }

 public static void main(String args[]){
  try{
   throwExceptions(1);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }
}
Output
java.lang.RuntimeException: Exception number 1
  

4. Throw keyword is used to throw exceptions from initializer block
import java.io.*;

class Stack{
 int size;

 {
  try{
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.println("Enter input");
   size = Integer.parseInt(br.readLine());
  }
  catch(Exception e){
   throw e;
  }
 }

 Stack()throws Exception{
 
 }

 public static void main(String args[]){
  try{
   new Stack();
   
   }
   catch(Exception e){
    System.out.println("Exception caught in main " + e);
   }
 }
}

Sample Output
Enter input
qwe
Exception caught in main java.lang.NumberFormatException: For input string: "qwe"


Note:
1. Static initializers cannot throw checked exceptions
2. Static initializers can throw unchecked exceptions like RuntimeException

throw clause                                                 try-resource statement                                                 Home