Handling Exceptions

Exception handling is managed via five keywords : try, catch, throw, throws and finally.

Code that can throw an error should be wrapped in a try block. When an error is thrown it is handled in a case block. They can be many case blocks, from the most specific to the general exception handler.

Here is the general syntax of the try-catch mechanism :

Syntax

try {
  //code that can throw an exception
}catch(ExceptionType ex){
//handle error
} finally {
//this code will always run  
}

The finally block is optional. From the chat program we will building, the IO.Socket throws a URISyntaxException exception, we can handle the exception as follows :

Socket mSocket;
try {
    mSocket = IO.socket("http://chat.socket.io");
} catch (URISyntaxException e) {
    e.printStackTrace(); //handle the exception here
}

Types of Exceptions

There are three kinds of exceptions :

  1. Checked exceptions
  2. Error
  3. Runtime exception

Checked Exceptions

These are exceptional conditions that a well-written application should expect and recover from. Checked exceptions should be specified as part of the method signature if they are not handled in the method.

Checked Exceptions

All exceptions that are not direct a subclass of Error and RuntimeException are checked exceptions. Some checked exceptions :

IOException
EOFException
NotSerializableException
ParseException

Error

These are exceptional conditions external to the application, and that the application cannot expect or recover from.

Error sub-classes

Here is a partial list of error exceptions :

OutOfMemoryError
VirtualMachineError
NoClassDefFoundError
StackOverflowError

Handling an Exception in an IDE

The code to create a socket object is wrapped within the try-catch block. Most IDEs makes handling exceptions a trivial task. In InteliJ IDE you can place your mouse cursor over the error and the IDE will offer a suggestion to wrap the code in a try-catch block for you.

Using the throws Keyword

If a checked exception is not handled in the method, the method should add a list of the unhandled checked exceptions as part of its method definition. The throws keyword is used to add the unhandled exceptions to the method signature.

Now the main method defines that it throws the URISyntaxException exception :

package edu.self;


import io.socket.client.IO;
import io.socket.client.Socket;

import java.net.URISyntaxException;


public  class Main {

    public static void main(String[] args) throws URISyntaxException {

        Socket mSocket;
        mSocket = IO.socket("http://chat.socket.io");
    }
}

results matching ""

    No results matching ""