Handling Exceptions in Java

We can handle exceptions using the try-catch-finally construct or explicitly tell as being handled elsewhere through the use of throws clause in that method signature.

The try-catch-finally block will look as below:

try{

//Some code that can throw IOException

}

catch(Exception ex)

{

//do some workaround.

//you can use the  IOException object ex for getting more details on the exception.

}

finally{

//always executed. So can do some cleanup activities.

}

We enclose the code that may throw an exception in the try block

The remaining statments within the try block are not executed after an exception is thrown for a statement. 

The try block is usually followed by one or more catch blocks.

Each catch block specifies an exception and if that exception or any of its subclasses occur, that catch block will be executed.

If none of the exceptions specified within the catch blocks match, the exeception is thrown to the caller of the method. Note that if it is a checked exception, there should be a catch block than can catch it (catch blocks for a parent exception can also catch it) or it should be declared with throws (it is ok even if you declare a parent exception in the throws).

The catch block is usually followed by a finally block. The finally block will be executed always irrespective of whether exception is thrown or not. So finally block is the best place to release resources like closing connections or files.

 

A try block should always be followed by a catch block and/or finally block or both as above. 

Few valid cases are:

  • A try block with only finally block.

  • A try block with only catch block.

  • A try block with catch block and finally block.

An invalid case is:

  • A try block without catch or finally

  • A try block with catch block and finally block, but catch block coming after finally block.

Order should be always try followed by catch followed by finally. For instance, you cannot have catch after finally.

If we are having multiple catch blocks, a parent exception catch block cannot come before a child exception catch block. This is because, if a parent exception catch block appears before a child exception catch block, parent exception catch block will catch the child exception as well and child exception catch block will never get executed.

 

Use of throws

We can handle exceptions using the try-catch-finally construct or explicitly tell as being handled elsewhere through the use of throws clause in that method signature.

We can declare a throws clause as:

public void myMethod() throws IOException

{

//method body with some code that can throw IOException

}

When you declare the throws clause for a checked exception like this, you don't have to handle that exception within the method (here myMethod), but any other code that will call this method need to either handle the exception or again declare a throws clause in its signature.

You can have throws clause for a constructor and throw an exception from the constructor. Whichever method or code that creates an object of that class with the new keyword using that constructor (e.g MyClass = new MyClass();) will have to handle the the exception or again declare throws on that method signature.

We can declare throws even on a main method. If an exception is thrown out of main () method, the JVM terminates the application and calls the exception’s printStackTrace () method.

We can declare unchecked exceptions with a throws clause. But as a good practice we don't include unchecked exceptions in a throws clause as they don’t have to be explicitly declared or handled.

 

Throws and throw

The throws keyword is used to declare that a mathod might throw an exception. 

The throw keyword is used to throw or rethrow an exception.

try{

throw new IOException();

}

catch(IOException ex)

{

//re-throwing as a custom exception

throw new MyCustomException(ex);

}

 

You can also write your own custom exceptions.

 

Inheritance and throws keyword

If a superclass method declares a throws clause for a checked exception, the overriding subclass method can't replace it with a broader one.

Child class however can replace it with a subclass of the parent exception or even remove the throws clause for that exception completely. This is because, when a subclass is used in the context of super class by assigning a subclass object to superclass, the caller expects only those exceptions that are declared on the superclass. So we can throw a subclass of the exception or even decide not to throw any, which will not create any problem for the caller. However if we add more exceptions, parent will not be expecting it and hence won’t be prepared to handle; hence compiler won't allow that. This restriction is not there for unchecked exceptions as their handling is optional. 

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)