Exceptions

An exception is a problem that arises during the execution of a program. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.

Exception Hierarchy:

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

exception hierarchy in java

To understand how exception handling works in Java, you need to understand the three categories of exceptions:

  • Checked Exception are all those Exception which requires being catched and handled during compile time. If Compiler doesn’t see try or catch block handling a Checked Exception, it throws Compilation error. Checked Exception is direct sub-Class of Exception. All those operations where we go outside jvm boundry or have more chances of failure like I/O, Database connection or execution, webservices calls etc, compiler forces us to handle these exception.
  • Unchecked Exception are those Exceptions whose handling is not verified during Compile time. Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object, accessing element outside an array size etc. , Unchecked Exception is direct sub Class of RuntimeException.
  • Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. The program cannot recover back if an error occurs. For example, if a stack overflow occurs, an error will arise.

Handling Exceptions

The main purpose of Exception of handling is for graceful termination of the program. Exception Handling dosen’t mean repairing the exception we have to define alternative way to continue the rest of code normally. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code.


package mynotes.exceptions;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class CheckException {

 public Connection getConnection() {

Connection connection = null;

try {
 Class.forName("com.mysql.jdbc.Driver");
 connection = DriverManager.getConnection(
 "jdbc:mysql://localhost:3306", "root", "admin");
 } catch (ClassNotFoundException e) {
 System.out.println("ClassNotFoundException");
 } catch (SQLException e) {
 System.out.println("SQLException=>"+e.getMessage());
}finally{
 System.out.println("FINAL");
 }

 System.out.println("DO SOMETHING");

return connection;
 }

 public static void main(String[] args) {
 CheckException aCheckException=new CheckException();
 Connection con = aCheckException.getConnection();
}

}

Output:


Exception => Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
FINAL
DO SOMETHING

As you can see above we have two statements in try blocks which throws two checked exceptions. I have not started my DB instance so it throwed a SQL exception. Notice that even though it throwed the excption finally blocks ran and the code outside try block also ran. If there is a runtime exception thrown that is not catched then the program terminates there.

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. The one senario when we are using system.exit(0) explicity then Jvm itself will be shutdown and there is no chance of executing the finally block.

 It is possible try block without catch block?

Yes It is possible try block without catch block using finally block.

What is difference between throw and throws keyword in Java?

Throws keyword is used in method signature to declare which checked exception method can throw, you can also declare unchecked exception, but that is not mandatory by compiler. This signifies lot of things like method is not going to handle Exception instead its throwing it, if method throws checked Exception then caller should provide compile time exception handling etc. On the other hand throw keyword is actually used to throw any Exception. Syntactically you can throw any Throwable (i.e. Throwable or any class derived from Throwable) , throw  keyword transfers control of execution to caller so it can be used in place of return keyword.


private void getDetails() {
 throw new UnsupportedOperationException("Not yet implemented");
 }

 private void readFile(String filename) throws IOException{

 if(!filename.contains("."))
 throw new IOException("File Name Invalid");
 }

Exception wrapping is wrapping is when you catch an exception, wrap it in a different exception and throw that exception. Here is an example:


try{

//some steps

} catch (SQLException e) {

throw new SQLException("SQLException");

 }

This will ensure that the your method returns from here and will not execute subsequent lines of code after try catch finally.

Exception chaining is a popular exception handling concept in Java, where another exception is thrown in response of an exception and creating a chain of Exceptions. This technique mostly used to wrap a checked exception into an unchecked or RuntimeException.

Can we catch Errors?

Yes we can.


package mynotes.exceptions;

import java.io.IOError;

public class CatchErrors {

 private void catchErrors(){
 throw new IOError(new Throwable ("IOError"));
 }

 public static void main(String[] args) {
 CatchErrors aCatchErrors=new CatchErrors();
 try{
 aCatchErrors.catchErrors();
 }catch(IOError e){
 System.out.println(e.getMessage());
 }

 System.out.println("After");
 }

}

Output:


java.lang.Throwable: IOError
After

Above we throw an Error. The compiler doesnt force us to use throws calls in the method. Compiler also doenst force us to catch this, however we wrote the catch block and capture th error. Note that the sysout at the end ran. It would not have run if the catch was not there.

Consider the following code:


try{
//some steps
}catch(IOException e){
System.out.println(e.getMessage());
}

In above senario, if your content in try block doenst throw a IOException, the compiler will show an error complaining unreachable catch block something. You can change it to Exception(so as it may consider that RuntimeException may occur) or remove it.

Exception in Parent Child overriding.

New method definition (which overrides the parent) in Child class can only throw all or none, or a subset of the checked exceptions (including their subclasses) that are specified in the throws clause of the overridden method in the superclass. It cannot throw any new Checked exception.

Declaring you own Exception

You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes:

  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a runtime exception, you need to extend the RuntimeException class.

NEW Exception handling syntax – from JAVA 7

Multi catch block and  Try with Resources


package mynotes.exceptions;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class NewJava7ExceptionSyntex {

 public Connection getConnection() {

Connection connection = null;

try {
 Class.forName("com.mysql.jdbc.Driver");
 connection = DriverManager.getConnection(
 "jdbc:mysql://localhost:3306", "root", "admin");
 } catch (ClassNotFoundException | SQLException e) {
 System.out.println("Exception => "+e.getMessage());
 }finally{
 System.out.println("FINAL");
 }

 System.out.println("DO SOMETHING");

return connection;
 }

public void readUsingTryWithResource() {
 try(BufferedReader br = new BufferedReader(new FileReader("MyText.txt"))) {
 StringBuilder sb = new StringBuilder();
 String line = br.readLine();

while (line != null) {
 sb.append(line);
 sb.append(System.lineSeparator());
 line = br.readLine();
 }
 String everything = sb.toString();
 System.out.println("File Contents==");
 System.out.println(everything);
 } catch (IOException e) {
 System.out.println("IOException => "+e.getMessage());
 }

}

public static void main(String[] args) {
 NewJava7ExceptionSyntex aNewJava7ExceptionSyntex=new NewJava7ExceptionSyntex();
 aNewJava7ExceptionSyntex.getConnection();
 aNewJava7ExceptionSyntex.readUsingTryWithResource();
 System.out.println("End");
 }

}

Notice the getConnection method. The exception are now written in one catch.
The try with resource , As name itself implies that now JVM is going to be handling all the external resource and make programmer free to bother about resource management.  If my java programmers use any external resources like file, printer or any devices to close after my program execution complete. Normally we close the resources at the end usually in the finally block. With the use of this java 7 guarantees that it will close these resources for you even if an exception occurs. This result in a neater code.

Grab all the code from my GitHub repository.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: