Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

try,catch and finally blocks in Exception Handling


The try Block:

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following:
try {
    code
}
catch and finally blocks . . .
The segment in the example labeled code contains one or more legal lines of code that could throw an exception.
To construct an exception handler for the writeList method from the ListOfNumbers class, enclose the exception-throwing statements of the writeList method within a try block. There is more than one way to do this. You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each. Or, you can put all the writeList code within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short.
private List<Integer> list;
private static final int SIZE = 10;

PrintWriter out = null;

try {
    System.out.println("Entered try statement");
    out = new PrintWriter(new FileWriter("OutFile.txt"));
    for (int i = 0; i < SIZE; i++) {
        out.println("Value at: " + i + " = " + list.get(i));
    }
}
catch and finally statements . . .
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it;

The catch Blocks:

 

You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.
try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}
Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.

The following are two exception handlers for the writeList method — one for two types of checked exceptions that can be thrown within the try statement:
try {

} catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException: "
                        + e.getMessage());
    throw new SampleException(e);

} catch (IOException e) {
    System.err.println("Caught IOException: "
                        + e.getMessage());
}
 

Catching More Than One Type of Exception with One Exception Handler:

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|):
catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}
Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.


The finally Block:

 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.

Note: 

If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Important:
The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.
If you are using Java SE 7 or later, consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed

 

READ MORE - try,catch and finally blocks in Exception Handling

Types of Exceptions

1. checked exception:
   
 These are exceptional conditions that a well-written application should anticipate and recover from. Example:suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

2. error:

 These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
Example: suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.

Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.

3.runtime exception:
  
 These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. 
Example: consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.



READ MORE - Types of Exceptions

What Is an Exception and it's Advantages?

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).

                                                        Call Stack

The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.

                                                       

Advantages of Exceptions:

Advantage 1: Separating Error-Handling Code from "Regular" Code

Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.

Advantage 2: Propagating Errors Up the Call Stack

 

A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods. Suppose that the readFile method is the fourth method in a series of nested method calls made by the main program: method1 calls method2, which calls method3, which finally calls readFile.
method1 {
    call method2;
}

method2 {
    call method3;
}

method3 {
    call readFile;
 

Advantage 3: Grouping and Differentiating Error Types

 

 


READ MORE - What Is an Exception and it's Advantages?

Program to demonstrate Floating-point arithmetic

/* Program to demonstrate Floating-point arithmetic */

class FloatPoint
{
    public static void main(String args[ ])
    {
        float a=10.5F,b=6.1F;
        System.out.println("a = "+a);
        System.out.println("b = "+b);
        System.out.println("a + b = "+(a+b));
        System.out.println("a - b = "+(a-b));
        System.out.println("a * b = "+(a*b));
        System.out.println("a / b = "+(a/b));
      
    }
}
READ MORE - Program to demonstrate Floating-point arithmetic

Java Compilation and Interpretation Process

Above figure shows compilation & Interpretation process

Following steps explains how it works:-

  •  We create  a program using program editor(eg. Notepad) and save it as filename.java file in specified directory.
  •  Then we compile it using javac command(eg. javac filename.java), A java compiler then convert .java file into .class file which is called as bytecode and this bytecode is platform independent can run on different platforms eg.Windows, Linux,MAC etc.
  • If any bugs found during compilation that should be fixed first then compiled again, If there is not any bugs found  then bytecode is created and handed over to JVM(java virtual machine) for interpretation.
  • JVM interpret class file by running java space class name command(eg. java filename)  as given in figure.
  • JVM has three components to interpret program first: Bytecode verifier which verifies bytecode, second: Class loader which loads required classes from java class library, third one is a JIT(just in time) compiler which compiles class file and convert it into machine readable format and then hand over to operating system.
  • If there any bugs(mostly logical) found during interpretation(by JVM) then one have to edit program to fix bugs and compile it again.If not any more bugs then final output will be displayed on screen.           


Note: It's not necessary to have same class name and file name. Thing is that file name is required during compilation and class name is required during interpretation but it would be great to use same name for class and file(file name is a name by which we store program).Also compilation process actually figure out any syntactical error while interpretation checks logical error.

READ MORE - Java Compilation and Interpretation Process

What is java?(precisely)


    What is java?
    • Developed by Sun Microsystems ( by James Gosling)
    • A general-purpose object-oriented language(while C++ is procedural plus object oriented)
    • Based on C/C++
    • Designed for easy Web/Internet applications


    Java Features:

      Note: features are always asked by interviewer


    1. Java is Simple:
    • Fixes some clumsy features of C++
    • No pointers
    • Automatic garbage collection
    • Rich pre-defined class library
         2.Java is Object oriented:
    • Focus on the data (objects) and methods manipulating the data
    • All functions are associated with objects
    • Almost all data-types are objects (files, strings, etc.)
    • Potentially better code organization and reuse
         3.Interpreted:
    • Java compiler generate byte-codes(and  not native machine code which is happens in C,C++)
    • The compiled byte-codes are platform-independent
    • Java byte-codes are translated on the fly to machine readable instructions at run-time (by Java Virtual Machine)
         4.Portable:
    • Same application can run on all platforms
    • The sizes of the primitive data types are always the same
    • The libraries define portable interfaces 
         5.Reliable:
    • Extensive compile-time and run-time error checking
    • No pointers but real arrays. Memory corruptions or unauthorized memory accesses are impossible
    • Automatic garbage collection tracks objects usage over time
         6.Secure:
    • Usage in networked environments requires more security
    • Memory allocation model is a major defense
    • Access restrictions are forced (private, public)
         7. Multithreaded:
    • multiple concurrent threads of executions can run simultaneously
    • utilizes a sophisticated set of synchronization primitives (based on monitors and condition variables paradigm) to achieve this
          8.Dynamic:
    • Java is designed to adapt to evolving environment
    • Libraries can freely add new methods and instance variables without any effect on their clients
    • Interfaces promote flexibility and reusability in code by specifying a set of methods an object can perform, but leaves open how these methods should be implemented
    • Can check the class type at run-time.

    READ MORE - What is java?(precisely)

     
     
     
     


    Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|