about Exceptions in Java

Exceptions in Java -
    An Exception is phenomenal condition, which can comes your program when program is executed. And this condition interrupt with program's normal flow.

    When any program face the exceptional condition, an exception object is made by JVM and program will be terminate.
            For prevent the termination of program, There is need to handle this situation.
    There are three type of exceptional event occurs.
   
1)Error
2)Checked Exceptions
3)Unchecked Exceptions


Errors -
Error can be occurs for network failure, Hardware failure or any other reason besides your programs. So you can not handle this through program code.

Checked Exceptions -
    Java compiler checks your code at compile time. If any exception occurs in this time error handler read this at compile time. This is called checked exceptions.
    IOException  are in the checked Exception.

Unchecked Exceptions -
    Unchecked exception occurs at runtime of your application. There are RuntimeException class is super class of all the Unchecked exception.

Exceptional Handling -
    In Java, Three type of exceptional handler components are try, catch and finally blocks.

Here is code with out handle the exception.

public class Test{
    public static void main(String[] args) throws CloneNotSupportedException {
        String s = "Hello how r u";
        String s1 = s.substring(0, 20);
        String ss = s+s1;
        System.out.println(ss);
    }
}

If you will run this program, exception will occurs at line no 4.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 20
    at java.lang.String.substring(Unknown Source)
    at com.iap.mnc.common.Test.main(Test.java:4)


so use try and catch block here.


public class Test{
    public static void main(String[] args) throws CloneNotSupportedException {
        String s = "Hello how r u";
        String s1=null;
        try {
            s1 = s.substring(0, 20);
        } catch (StringIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        String ss = s+s1;
        System.out.println(ss);
    }
}

now exception is handled by try catch block. Then next line is also execute.

Now output will be -
   
    java.lang.StringIndexOutOfBoundsException: String index out of range: 20
    at java.lang.String.substring(Unknown Source)
    at com.iap.mnc.common.Test.main(Test.java:7)
Hello how r unull

Finally block –
    Finally block will always execute when try block exist.So finally block is used for release all the object and connections which is used in try block.

Comments

Recent Post

Recent Posts Widget

Popular posts from this blog

Capture image from webcam java code, examples

Use of req.query, req.params and req.body in NODE JS

How to capture finger prints in java