Skip to main content

What is exception handling ?


An exception is an object that is generated at run-time to describe a problem encountered during the execution of a program.Some causes of exceptions are division by zero, array index out of bound, interrupted I/O, end of file, etc.
Java allows to handle exceptions that occur during the execution of a program.
****Syntax****
try{try block}catch(ExceptionType arg1){catch code}catch(ExceptionType arg2){catch code}finally{finally block}
****Try block****
The try statement contains a block of statements closed by braces. This code will be monitored for exceptions. If any exceptions occur, it will be thrown using the throw statement.Immediately after the try block there is a sequence of catch blocks. Each catch block begins with catch statement. The argument is the exception object that contains
When a problem occurs during execution of the try block, the JVM immediately stops executing the try block and looks for a catch block that can process that type of exception.
****Working****
When an error occurs, the search for the catch statement begins from the first catch block. If the arguments are matched then those statements are executed, else the remaining catch blocks are searched.When a catch blocks completes execution, control passes to the statements in the finally block.
The java compiler ensures that the finally block is executed any how.  When a try block completes without errors, the finally block executes.Each try block must have at least one catch or finally block. Else the compiler will generate errors.
****example****
class Divider{public static void main(String s[]){try{System.out.println("Before Division:");int i=Integer.parseInt(s[0]);int j=Integer.parseInt(s[1]);System.out.println(i/j);System.out.println("After Division:");}catch(ArithmeticException e){System.out.println("ArithmeticException");}catch(ArrayIndexOutOfBoundsException e){System.out.println("ArrayIndexOutOfBoundsException");}catch(NumberFormatException e){System.out.println("NumberFormatException");}finally{System.out.println("Finally");}}}
***The throw statement***
Normally, exceptions are generated by the JVM when certain run-time errors occur. It’s also possible for a program to explicitly generate an exception. To achieve this the throw statement is used.Syntax: throw <object>;Here, the object must be of type java.lang.Throwable else the compiler will generate errors.
Inside a catch block, one may throw the same exception object that was provided as an argument.
Syntax:catch(ExceptionType arg){…………….throw arg;……………}
A new exception object can be created and thrown as given below:Syntax:throw new ExceptionType(arg);When throw statement is encountered, a search for a matching catch block begins. Any subsequent statements in the same try or catch block are not executed.
****Exception & Error Classes****
Each catch clause must have exactly one parameter whose type is Throwable. Java compiler generates error if the parameter is not specified of Throwable type.Throwable class is the super class of all exception and error classes.
****Throwable constructor****
The Throwable class provides the following constructors:Throwable()Throwable(String msg)Here msg is a string that describes the problem.
***Methods provided by Throwable***
Throwable class provides two methods getMessage() and printStackTrace().getMessage() returns the string that was provided to the constructor. The prototype is:String getMessage()The method displays information about the program stack at the time of problem. This method displays the stack trace on standard O/P stream. The prototype is :void printStackTrace()
***Error class***
Error class extends Throwable. It contains all the subclasses like class format error, stack overflow, memory exhaustion, internal errors etc. that can be encountered by the JVM.
***Exception class***
Exception class extends Throwable. It has subclasses to represent run-time errors.It has the following constructors:Exception()Exception(String msg)Here msg is a string that describes the problem.
***RuntimeException class***
The RuntimeException class describes runtime exceptions. It provides the following constructors:RuntimeException()RuntimeException(String msg)
***throw clause***
A throw clause can be used in a constructor declaration for providing, information regarding the method, which generates the exception. This helps other programmers to know about the type of exception thrown by that method.
The general form for using the throw clause is as given below:consModifiers <class_name>(args) throws exceptions{………body of Constructor}Here consModifiers are optional set of modifiers. The class_name is the name of the class. arg are the optional constructor parameter. A list of some exception that can be generated by the constructor is specifie
The throw clause can be used in a method declaration as shown below:mthModifiers r_type Meth_name(arg) throws exceptions{}Here, mthModifiers are optional set of modifiers, r_type is the return type, Meth_name is the name of the method. arg are the optional constructor parameter. A list of some exception that can be generated by the constructor is specified by exceptions.
The Java compiler checks for each constructor and method to determine the type of exceptions it can generate.Other than RuntimeException subclasses, all other subclasses of Exception are to be declared.A Java compiler also generates an error if there is a catch block for an exception type that can’t be generated by the try block.
***custom Exception***
Its possible to create our own exception classes in order to handle application specific problems.This can be done by creating the subclasses of the Exception.throw statement can be used to throw an instance of the exception.One must catch or declare this exception in all methods in which it occurs if it is not a subclass of RunTimeException.
Classes ExceptionA and ExceptionB extends Exception. c() creates a random number and uses it to determine which type of exception to throw. throw clause indicates it can generate both of these exception types. Method b() has a throw clause that includes only ExceptionA, because ExceptionB is handled by a catch block in that method. Method a() has a catch block that handles any exception. Therefore throw clause is not required.

Comments

  1. It's very easy to learn ........
    Thanks For Blog.........

    ReplyDelete

Post a Comment

Popular posts from this blog

What is Servet ?

A servlet is a java class that extends an application hosted on a web server. Handles the HTTP request-response process (for our purposes) Often thought of as an applet that runs on a server. Provides a component base architecture for web development, using the Java Platform The foundation for Java Server Pages (JSP). Alternative to CGI scripting and platform specific server side applications.

Latest Java 6 to 10

6. What are the access modifiers in java ? There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly. 7. What is are packages? A package is a collection of related classes and interfaces providing access protection and namespace management. 8. What is meant by Inheritance and what are its advantages? Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses. 9. What is the difference between superclass and subclass? A super class is a class that is inherited whereas sub class is a class that does the inheriting. 10. What is an abstract class? An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.

51 to 55 Java Questions

51. What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 52. What will happen to the Exception object after exception handling? Exception object will be garbage collected. 53. Difference between static and dynamic class loading. Static class loading: The process of loading a class using new operator is called static class loading. Dynamic class loading: The process of loading a class at runtime is called dynamic class loading. Dynamic class loading can be done by using Class.forName(….).newInstance(). 54. Explain the Common use of EJB The EJBs can be used to incorporate business logic in a web-centric application. The EJBs can b...