Home > java > Exception handling in java

Exception handling in java

Exception handling in java

Exception handling in Java is a very important topic.it is the main features of Java in a programming language is not only used in Java it is also using .net or any other object-oriented programming language. Today we are going to discuss exception handling in java along with we will perform some program which helps for better understanding.

Did you know

What is meant by Exception Handling


Basic aim of exception handling is to build a robust or strong application which helps the programmer and application user to give a better and consistent result. In any object-oriented programming language. 

In software development basically three types of error.

1) Compile time error.
2) Logical error.
3) Runtime error.

Compile time error: It is an error which is occurring at compile time syntax is not followed correctly. we will be solved by the programmer at development or a production level.

Logical error: Logical error are those which are occurring at execution or runtime because of mis-interpretation of logic. The logical error always give wrong output and inconsistent result and it will be solved by the programmer

Runtime errors: Runtime errors are those which are occurring at runtime due to invalid input into by application user.

The languages like C, C + +, Pascal, COBOL it is whose application are treated as we because these a language does not contain a facility call exception handling.

The language and technologies like Java and .net and their respected application treated as the robust or strong because these languages contain exception handling facility.

Point to Note:


1. When an application user enters valid input, we get runtime errors.
2. Runtime errors always generate system and Technical error messages.
3. Runtime error of Java program is known as an exception.
4. Exception always generates a system or technical error message (invalid input always causes exception).
5. Whenever an exception occurs in the Java program, then program execution is abnormally terminated CPU  control comes out of program flow and JVM generate system error messages.

What is exception in java


In the Software Industry generating system error messages are not recommended but the industry is always recommended for user-friendly year messages.

Definition of exception handling:

The process of converting system your messages into user-friendly your messages is called exception handling.

What is the Java exception

“Each and every action/task/operation must be performed with respect to object in exception handling”

We know that whenever an exception occurred in the Java program then program execution is abnormally terminated, CPU controls come out of the program flow and JVM generate system error messages.

Generating system error messages is an action or task and it can perform with respect to an object. Programmatically, generating system error messages required object creation and to create an object we require a class this class is known as Exception class.

Hence JVM will create an object of appropriate Exception class and generate system error messages when application user entered invalid input.

What are the types of exceptions in Java


If Exception class is developed by Sun Microsystem developers then it is known as the predefined exception. If the exception classes developed with a Java Program then it is called the user-defined exception.

Based on the development of exception, exceptions are classified into the two types.

1) Pre-defined / build-in Exception
2) User-defined Exception.

Predefined exceptions are those which are developed by sun microsystem and supplied as a part of Java software or JDK and they always deal with Universal problems. Some of the universal problems are,

1) Division by zero problems.
2) An Invalid number from formats.
3) An invalid bound of array etc.

The user-defined exceptions are those which are developed by Java program and supplied as a part of their project and they always used for dealing with the common problem. Some of the common problems,

1) Try to enter invalid salary for an employee.
2) Try to Deposit invalid amount in the balance of an account. 
3) Try to enter an invalid number of passport.
4) Try to enter the invalid username and password in the login page.

Types of Pre-defined Exception


There are two types of predefined exception.

1) Asynchronous exception
2) Synchronous exception

Asynchronous exception


These exceptions are those which always will be the hardware problem and external problems. Ex:- Memory failure  problem, Mouse keyboard failure.

Sun Microsoft developer has not developed complete API to deal for asynchronous exception i.e Specially developed API and as of now industry we are not using asynchronous exceptions.

To deal with all types of Asynchronous exceptions we have a predefined class call Java.lang.error. In other words Java.lang. Error is a superclass for all Asynchronous exception.

Java.lang.Error
java.lang.StackOverFlowException

Synchronous Exception


Synchronous Exception always deals with programmatic runtime errors.Synchronous Exceptional classified into two types.

1) Checked Exception
2) Unchecked Exception

Checked Exception


Checked Exceptions are those which are the direct subclass of java.lang.Exception, or the exceptions which are occurring at runtime. It will show them as an error in compile time that is compile-time regarding Exception.

Java.lang.Exception
java.lang.FileNotFoundException

Unchecked Exception


Unchecked exception are those which are the direct subclass of java.lang.RuntimeException.

Java.lang.Exception
Java.lang.RuntimeException

Java.lang.RuntimeException
java.lang.ArithmeticException

Q. what are the three main classes used for dealing with all types of exceptions ?

1) java.lang.Error, used to deal with all asynchronous  exception.
2) java.lang.Exception used to deal with all synchronous unchecked exceptions.
3) java.lang.RuntimeException is used to deal with all synchronous unchecked exceptions.

Hierarchy of Exception Handling


It always makes us understand, how the feature inherited from topmost best class to intermediate basic classes and from intermediate base classes to bottommost classes.

Hierarchy of Exception handling

1.In the above hierarchy chart java.lang.Object is the superclass of all the classes in Java and it provides garbage collection facility to its subclasses for collecting unused memory space.

2.java.lang.Throwable is the superclass for all the Exception in Java. it is used for deciding which type of exception occurs in the Java program either synchronous or asynchronous.

3.Java.lang.Error is the superclass all the Asynchronous exceptions.

4.Java.lang.Exception is the superclass for all synchronous checked exception.
5.Java.lang.RuntimeException is the superclass for all synchronous unchecked exception.

Note: Even though there is multiple exceptions occur in a single program at any point of JVM can process only one exception at a time but not multiple exceptions.

Flow of exception occurrence


Whenever we write a Java Program there is a possibility of occurring many exceptions. The following diagram gives a sequence of steps of internal flow of exception

Interflow of Exception Handling

I) Application users enter valid input to the Java program then JVM can process the Java program with valid Input and give a valid output.

1) Application user enters invalid input to the Java program.
2) JVM can not process the Java program with invalid Input and JVM contact to JRE(JVM+Java API) for obtaining exception subclass.
3) JRE contacts to java.lang.Throwable for obtaining which type of exception occurs in the program.
4) java.lang.Throwable is a superclass for all the exceptions in Java and it decides types of exception and gives the same message back to JRE.
5) JRE for the contact to Java exception API further contacts to java Exception API for obtaining exceptions of class.
6.1,2,3) java exception API execute 6.1(java.lang.Error for Asynchronous Exception) or 6.2(java.lang.Exception for synchronous checked Exception) or 6.3(java.lang.RuntimeException for synchronous Unchecked Exception).
7) java exception API gives appropriate exception subclass to JRE.
8) Their gives exception subclass back to JVM.
9) JVM will create an object of appropriate exception subclass. ex:- for the division of two numbers program. If we enter 10 and 0 as an input(invalid input) that internal JVM will create an object of arithmetic exception. Programmatically as shown below ArithmeticException ae= new ArithmeticException(“/by zero”);
10) JVM will generate by default system error message.
11) Java program convert default system error message into user-friendly  error messages.
12) By using exception handling mechanism.

Why are we using exception handling in Java


In the software development, it is not recommended to generate system error message and recommended to generate a user-friendly error message. Java programmer convert system error message into user-friendly and messages by making use of exception handling concept.

Exception handling in java


We know that whenever an exception occurred in the Java program, jVM generates system error message.
Generating system error message is not recommended in the Real world and industry is highly recommended to generate user-friendly error message by making use of exception handling concept.

Handling the exceptional means converting system error messages into a user-friendly error message to do this process as a part of exception handling we are having 5 keywords they are,

1) try
2) catch
3) finally
4) throws
5) throw

The syntax for Handling Exception


try
{
    Blockk of Statement() 
    which cause problems at runtime 
}
catch(Type of Exception1 obj1)
{
    Blockk of Statement() 
    which provide user-friendly message
}
catch(Type of Exception2 obj2)
{
   Blockk of Statement() 
   which provide user-friendly message
}
....
....
....
catch(Type of ExceptionN objn)
{
   Blockk of Statement() 
   which provide user-friendly message
}
finally
{
   block of statement()
   which will execute compulsary
}

try block


1) In this block, we always write a block of statement which causes a problem at runtime or what are all the blocks of statements generating exceptions.
2) When the exception occurred in the try block, program floor is abnormally terminated, JVM control comes out of try block and executes appropriate catch block
3) After executing appropriate catch block JVM control Never Goes to try block again to execute the rest of the statements even we use the return statement in the catch block.
4) Each and every try block must be immediately followed by catch block it means no intermediate statements are allowed between try and catch block.
5) For each and every try block we must write at least one catch block. it is highly recommended to the Java program to write multiple catch blocks for generating multiple user-friendly error messages.
6) One try block can contain another try block it means nested or inner try block can be possible.

catch block:


1) It is the block in which we write blocks of a statement and they provide user-friendly error messages. In other words, catch block will convert system error messages into user-friendly error messages.
2) catch block will execute provided exception occurs in the try block.
3) It is highly recommended to the program to write multiple catch blocks to generate multiple user-friendly air messages.
4) At any point of time JVM can execute only one catch block among multiple catch blocks.
5) Programmatically in the catch block declaration of appropriate exception object done by Java programmer and the internally exception will reference by JVM.
6) We can also write try and catch block as a part of catch blocks.

Example:

catch block in java

finally block


1) In this block we write the block of statements which will use to release/close/terminate the resource like file/database.
2) finally block will execute compulsory.
3) Writing fly finally block is optional.
4) It is highly recommended to the Java program to write one finally block per Java program.
5) In finally Block we can also write try and catch block.

Program flow with Exception handling


case1: If an exception occurred then,

1)A part of try block will execute.
2)An appropriate catch block will execute.
3)Finally, a block will execute (if we write)

case2: If no exception occurred then,

1)A complete try block will execute.
2)Finally, a block will execute (if we write)

Division.java

public class Division 
{
  public static void main(String[] args) 
  {
    try
    {
      String s1=args[0];
      String s2=args[1];
      //Type Casting from String to Integer
      int x=Integer.parseInt(s1);
      int y=Integer.parseInt(s2);

      int z=x/y;
      System.out.println("Division is:"+z);
    }
    catch(ArithmeticException ae)
    {
      System.out.println("Don't enter Zero at Denominator");
    }
    catch(NumberFormatException ne)
    {
      System.out.println("Don't enter Alpha Numeric values");
    }
    finally
    {
      System.out.println("I am from Finally block");
    }
  }
}

OUTPUT

E:\java>javac Division.java

E:\java>java Division 12 6
Division is:2
I am from Finally block

E:\java>java Division 12 0
Don't enter Zero at Denominator
I am from Finally block

E:\java>java Division 12 h6
Don't enter Alpha Numeric values
I am from Finally block

E:\java>

throws Keyword


Throws is a Keyword which will express or describe the type of exception occurring in the body of the common method

Throws is a keyword which gives an indication to the specific method to place common exception method under try and catch block for generating user-friendly error messages.

According to the industry standard, specific methods should always contain try and catch blocks for handling the exceptions and generates user-friendly specific and it should not contain throws keyword.

Common method java should always contain throws keyword for expressing the type of exception occurring as a part of the common method body and it is not recommended to contain try and catch blocks.

The place of using throws keyword is always as a part of method heading.

Syntax

returnType methodName(List of formal parameter if any) throws(ClassName1,className2...classNamen)
{
   Block of statement
}

In the above syntax ClassName1, ClassName2, classNamen represents the name of the Exception classes and they may belong to either pre-defined or user-defined or both.

Example: public static int parseInt(String) throws java.lang.NumberFormatException.

parseInt(String): Method heading contains throws keyword so that it is one of the common exception methods and it must be always placed within a try and catch block.

Division.java

package com.ravi.java;
public class Division 
{
  public void division(String s1,String s2) throws ArithmeticException,NumberFormatException
  {
    int x=Integer.parseInt(s1);
    int y=Integer.parseInt(s2);

    int z=x/y;
    System.out.println("Division is:"+z);
  }
}

In com.ravi.java.Division class division method is one of the user-defined, common exceptions and it must be always written within a try and catch block.

Main.java

import com.ravi.java.Division;
public class Main 
{
  public static void main(String[] args) 
  {
    try
    {
      Division d=new Division();
      d.division(args[0],args[1]);
    }
    catch(ArithmeticException ae)
    {
      System.out.println("Don't enter Zero at Denominator");
    }
    catch(NumberFormatException ne)
    {
      System.out.println("Don't enter Alpha Numeric values");
    }
    catch(ArrayIndexOutOfBoundsException ab)
    {
      System.out.println("Please enter only two values from CMD");
    }
    finally
    {
      System.out.println("I am from Finally block");
    }
  }
}

OUTPUT

E:\java>javac -d . Division.java

E:\java>javac Main.java

E:\java>java Main 12 6
Division is:2
I am from Finally block

E:\java>java Main 12 0
Don't enter Zero at Denominator
I am from Finally block

E:\java>java Main 12 2rjt6
Don't enter Alpha Numeric values
I am from Finally block

E:\java>

Rethrowing the Exception


The first method is throwing the exception to the second method and the second method is again throwing the first method exception to the third method with respect to the second method first method related exception is known as rethrowing the exception.

Example: In the above program parseInt(first method) is throwing NumberFormatException to division method(second method) and the division method intern throws NumberFormatException to parseInt(first method) to the main method(third method) with respect to division(second method) NumberFormatException of parseInt methods is known as rethrowing the exception.

How to handle unknown exception in java


Whenever we write a Java Program there is a possibility of a number of exceptions in Java program and all these exceptions may not be aware of the type of exception occurring in Java program.

If a Java programmer is not aware of a specific type of exceptions in the JAVA programmer may not be able to generate a specific user-friendly error message.

It is highly recommended to know about an unknown exception. In Java programming, we have three approaches for finding the detail about unknown exceptions.

1) By using an object of Java.lang.Exception.
2) By using printStackTrace() method.
3) By using getMessage() method.

1)By using an object of Java.lang.Exception.


We know that Java.lang.Exception is the superclass for all synchronous exception and according to the concept of dynamic binding an object of Java.lang.Exception is knowing about all its subclasses.

An object of Java.lang.Exception always gives the following details.

1) Name of the unknown exception.
2) Nature of the message.

try   
{ 
5:     ................ 
6:     int c=10/0; 
7:     ................   
}   
catch(Exception e)   
{    
   e.printStackTrace(); //java.lang.ArithmeticException: ===> name of the exception;
   // /by zero =======> nature of message     
} 

2) by using printStackTrace()


It is one of the predefined method present in java.lang.Throwable class and it is further inherited by both java.lang.Error and java.lang.Exception.

By using the printStackTrace() method we can find the following details.

1) Name of the unknown exception.
2) Nature of the message.
3) Line number where the exception occurs.

The prototype of printStackTrace() method is shown below,

public void printStackTrace()===>java.lang.Throwable
Since this method is returning void as the return type, it should not be called as a part of Sop or Sep.

Ex:- System.out.println(e.printStackTrace());  //Invalid call
System.out.println(e.printStackTrace());  //Invalid call

e.printStackTrace(); //valid

In Java programming is any method return void as a return type, it should not be called as a part of Sop or Sep.

Exp.java

class Exp 
{ 
  ..................... 
  ..................... 
  try 
  { 
5:     ................ 
6:     int c=10/0; 
7:     ................ 
  } 
  catch(Exception e) 
  { 
    e.printStackTrace(); //java.lang.ArithmeticException: ===> name of the exception 
    // /by zero =======> nature of message 
    // at Exp.java:6 ===> line number 
  }
}

When an exception occurred in the Java program before the program execution is an abnormally terminated, the exception detail will be pushed into the stack.

Stack memory

1) Name of exception.
2) Nature of Exception.
3) Line number.

3)By using getMessage()


It is one of the predefined method present in java.lang.Throwable and it is further inherited by both java.lang.Error and java.lang.Exception.
With getMessage() method we can obtain only the nature of the message
The prototype of getMessage() method is shown below.

public String getMessage()  ===>java.lang.Throwable

Example:

try
{
  ................................
  ..............................
  int z=12/0;
}
catch(Exception e)
{
  System.err.println(e.getMessage()); //print : /by zero
}

User /Secondary/Custom/Programmer Defined Exception


A user-defined exception are those which are developed by Java programmer and supplied as a part of their project and they always deal with common problems.

Some of the commons are,
1) Trying to enter invalid salary to an employee.
2) Trying to deposit negative value in the balance of the account.
3) Trying to enter an invalid number of the password.
4) Trying to enter invalid username and password etc.

When the application user enters invalid inputs to the JAVA application program execution is abnormally terminated by creating an object of appropriate exception subclass. If these exceptions are developed by Sun Microsystem then they are called predefined exception or if these exception subclass developed by Java programmers then they are called the user-defined exception.

what are all guidelines are followed by Sun Microsystem developer for development of predefined exception the same guidelines will follow by the Java programmer for development of user-defined exceptions.

Steps/guidelines for the development of user-defined exception. Sun MicroSystem developers have prescribed the following guidelines for the development of user-defined exceptions.


1) Choose an appropriate package for placing user-defined exception subclasses for common access and ensure package statement must be the first executable statement.
2) choose an appropriate user-defined class and ensure whose modifier must be public.
3) The class which is selected in a step-2 must extend either java.lang.Exception or java.lang.RuntimeException for inheriting feature of exception. To stop the program execution abnormally when the application user enters invalid input. Hence step-2 class is known as user-defined exceptions subclass.
4) Each and every user-defined exception subclass contains a parameterized constructor and must take String as a parameter. Here String parameter represents the nature of the message.
5) Each and every user-defined exceptions subclass parameterized constructor must call either parameterized java.lang.Exception or java.lang.RuntimeException by making use of super(msg). The reason for writing super(msg) is that if any specific exception occurs in the java program and if such a specific exception are not handled by Java programmer then such a specific exception will be handled by either java.lang.Exception or java.lang.RuntimeException.
6) whatever the user-defined exceptions class, we are placing in the package such class name must be given as a filename with an extension “.Java”.

Write a Java Program for developing user-defined exceptions subclass for dealing with the Negative salary of an employee.


NegSalary.java

package com.ravi.java;
public class NegSalary extends Exception
{
  public NegSalary(String s)
  {
     super(s);
  }
}

compile as: javac -d . NegSalary.java

Write a Java Program for developing user-defined exceptions subclass for dealing with the Positive salary of an employee.


PosSalary.java

package com.ravi.java;
public class PosSalary extends RuntimeException
{
  public PosSalary(String s)
  {
    super(s);
  }
} 

compile as: javac -d . PosSalary.java

In the above two programs NegSalary.java and PosSalary.java used to deal with User-defined Exception.

In software development, as a part of user-defined exception development, we developed three types of application in three phases,
1) Development of programmer or user-defined exceptions subclass.
2) Development of programmer for user-defined common classes original classes.
3) Development of programs on user-defined the specific class.

1) Development of programmer/user-defined exceptions subclass.
Example: NegSalary.java and PosSalary.java are come under programmer/user-defined exceptions subclass.
2) Development of programmer for user-defined common classes original classes.
This phase of classes always deals with the common requirement in the project. These classes make use of user-defined common subclasses.

Example: Write a java program which defined common classes for dealing with the salary of all the Employees.


Employee.java

package com.ravi.emp;
import com.ravi.java.NegSalary;
import com.ravi.java.PosSalary;
public class Employee
{
  public void decideSal(String s) throws NegSalary,PosSalary,NumberFormatException
  {
    int sal=Integer.parseInt(s);
    if(sal<=0)
    {
	NegSalary ns=new NegSalary("Invalid Salary");
	throw(ns);
    }
    else
    {
	PosSalary ps=new PosSalary("Valid Salary");
	throw(ps);
    }	
  }
}

compile as: javac -d . EmpSal.java

3) Development of programs on user-defined the specific class.
These classes are always dealing with a specific/individual requirement and these classes make use of common classes which are developed in the second phase and makes of exceptions subclasses developed in the first Phase.

Write a Java Program which will check the salary of the employee


EmpSal.java

import com.ravi.emp.Employee;
import com.ravi.java.NegSalary;
import com.ravi.java.PosSalary;
import com.ravi.emp.Employee;
public class EmpSal
{
  public static void main(String[] args)
  {
    try
    {
        String sal=args[0];
	Employee e=new Employee();
	e.decideSal(sal);
    }
    catch(NegSalary ns)
    {
        System.err.println("Don't enter Zero or Negative Salary");
    }
    catch(PosSalary ps)
    {
	System.err.println("Valid Salary ");
    }
    catch(NumberFormatException nf)
    {
	System.err.println("Don't enter Alpha numeric Number");
    }
    finally
    {
	System.out.println("I am from FinallyBlock");
    }
  }
}

compile as: javac Employee.java

E:\java>javac -d . NegSalary.java

E:\java>javac -d . PosSalary.java

E:\java>javac -d . Employee.java

E:\java>javac EmpSal.java

E:\java>java EmpSal 0
Don't enter Zero or Negative Salary
I am from FinallyBlock

E:\java>java EmpSal 120000
Valid Salary
I am from FinallyBlock

E:\java>java EmpSal 12af
Don't enter Alpha numeric Number
I am from FinallyBlock

E:\java>

Throw keyword


Throw is the keyword is always used for generating/raising the exception which is occurring as a part of the method body. or, Throw the keyword used for carrying the created exception is a part of the method body and handover to throws keyword. The place of using throw keyword is always as a part of the method body.

when we use throw keyword as a part of the method body, it is always mandatory to the programmer to use throws keyword as a part of method heading.

Syntax-1

<classsName> objName = new <className>(msg); 
   throw(objName);

Here,<classsName> represents name of Exception subclass.

Example,

NegSalException no=new NegSalException("Invalid salary");
throw(no);

Syntax-2 (throw keyword along with throws keyword)

returnType methodName(List of Parameter) throws <className1>,<className1>...<classNameN> 
{ 
  if(TestCondition) 
  { 
    <className1> obj1=new <className1>(msg); 
    throw(obj1); 
  } 
........... 
........... 
  if(TestCondition) 
  { 
    <classNameN> objN=new <classNameN>(msg); 
    throw(objN); 
  } 
}

In the above syntax <className1>…<classNameN> represents either user-defined Exception subclass or pre-defined Exception subclass or both.

Example: In above example decideSal() method of com.ravi.emp.Employee class (Employee.java).

Interview Question


Q. What is difference between Error and Exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you can not repair them at runtime.

While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.

Q How can you handle Java exceptions?

Below are the keywords used for Exception handling in java

  • try
  • catch
  • finally
  • throw
  • throws

Q. What are the differences between Checked Exception and Unchecked Exception?

Checked Exception

  • The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions.
  • Checked exceptions are checked at compile-time.
  • Example: IOException, SQLException etc.

Unchecked Exception

  • The classes that extend RuntimeException are known as unchecked exceptions.
  • Unchecked exceptions are not checked at compile-time.
  • Example: ArithmeticException, NullPointerException etc.

Q. What is the difference between final, finally, and finalize in Java

Final: final is a keyword used to restrict access class, method and variable. We can’t  inherite final class, final method can not  be overridden and final variable value can not  be changed. Kefer refer below example below Example

 

class FinalVarExample 
{
 public static void main( String args[])
 {
  final int a=10;   
  // Final variable
   a=50;             
  //Error as value can't be changed
 }
}
finally: finally is a block which is use in Exception handling and the codes present in finally block it execute compursory.Real time example used for database or file close activity.
class Finally
{
 public static void main(String args[])
 {
  try 
  {
   int x=13;
  }
  catch(Exception e) 
  {
    System.out.println(e);
  }
  finally 
  {
    System.out.println("finally block execute compulsory");
  }
 }
}

finalize: it is a method which perform clean up activity just before garbage collection.

class Finalize_Method
{
 public void finalize() 
 {
  System.out.println("finalize is method called");
 }
 public static void main(String args[])
 {
  Finalize_Method f1=new Finalize_Method();
  Finalize_Method f2=new Finalize_Method();
  f1= NULL;
  f2=NULL;
  System.gc();
 }
}

 Q. What are the differences between throw and throws

throwthrows
1) throw is a keyword used for raising or generating an exception which is occurring as a part of method body.1) throws is a keyword used for giving indication to the specific method to place common exception method under try and catch block.
2) The place of using throw keyword is always as a part of method body2) The place of using throws keyword is always as a part of method heading
3) When we write throw keyword as a part of method body then it is mandatory to the java programmer to write throws keyword with method heading.3) When we write throws keyword as a part of method heading then it is optional to the java programmer to write throw keyword with method body.

Q6. What is exception hierarchy in java

exception hierarchy in java

 

Q. How to create a custom Exception

1) Choose an appropriate package for placing user-defined exception subclasses for common access and ensure package statement must be the first executable statement.
2) choose an appropriate user-defined class and ensure whose modifier must be public.
3) The class which is selected in a step-2 must extend either java.lang.Exception or java.lang.RuntimeException for inheriting feature of exception. To stop the program execution abnormally when the application user enters invalid input. Hence step-2 class is known as user-defined exceptions subclass.
4) Each and every user-defined exception subclass contains a parameterized constructor and must take String as a parameter. Here String parameter represents the nature of the message.
5) Each and every user-defined exceptions subclass parameterized constructor must call either parameterized java.lang.Exception or java.lang.RuntimeException by making use of super(msg). The reason for writing super(msg) is that if any specific exception occurs in the java program and if such a specific exception are not handled by Java programmer then such a specific exception will be handled by either java.lang.Exception or java.lang.RuntimeException.
6) whatever the user-defined exceptions class, we are placing in the package such class name must be given as a filename with an extension “.Java”.

Q. What is a finally block? Is there a case when finally will not execute?

finally is a block which is use in Exception handling and the codes present in finally block it execute compursory.Real time example used for database or file close activity.
Yes, finally will not be executed if the program exits either by calling System.exit() or by causing a fatal error that causes the process to abort.

Q. What are the advantages of exception handling in Java


The main advantage of Exception handling is, Exceptional handling in Java is used to convert System error message into the user-friendly error message.

Q. Can we throw multiple exceptions in Java


Yes, We can throw multiple Exception in java by using throw keyword by method body and throws will take care about all the exception, throws keyword should be declared with method heading while the declaration of the method. Whenever we write to throw one or multiple exceptions from method body then it is mandatory to write throws keyword with respected Exception class. We can write code to throw multiple exceptions in java but while execution JVM will throw only one exception and the program will terminate abnormally. Kindly refers below program for better understanding.

public class Throw_Multiple_Exception extends Exception
{
	int division_By_Zero(int nominator,int denominator) throws ArithmeticException,NumberFormatException
	{
		int result;
		if(denominator==0)
		{
			ArithmeticException ae=new ArithmeticException("Don't Enter Value of Denominator is ZERO");
			throw(ae);
		}
		else
		   result=nominator/denominator;
		return result;
	}
	public static void main(String args[])
	{
		String s1=args[0];
		String s2=args[1];
		int x=Integer.parseInt(s1);
		int y=Integer.parseInt(s2);
		Throw_Multiple_Exception tme=new Throw_Multiple_Exception();
		int z=tme.division_By_Zero(x,y);
		System.out.println(z);
	}
}

OUTPUT with Exception and without Exception,

E:\java>javac Throw_Multiple_Exception.java

E:\java>java Throw_Multiple_Exception 12 6
2

E:\java>java Throw_Multiple_Exception 12 0
Exception in thread "main" java.lang.ArithmeticException: Don't Enter Value of Denominator is ZERO
        at Throw_Multiple_Exception.division_By_Zero(Throw_Multiple_Exception.java:8)
        at Throw_Multiple_Exception.main(Throw_Multiple_Exception.java:22)

E:\java>java Throw_Multiple_Exception 12 1k
Exception in thread "main" java.lang.NumberFormatException: For input string: "1k"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at Throw_Multiple_Exception.main(Throw_Multiple_Exception.java:20)

E:\java>

As we can see in above example, in “division_By_Zero(int nominator, int denominator)” we throws two exceptions but while execution it catches only one at a time because whenever JVM catch the first exception after that it terminates the program abnormally and controls come out from execution.

Q. Can we handle the exception with Try and without catch block?


yes, We can handle with the help of finally block but we can’t handle exception alone by using try bloc only. It is compulsory to use in combination of try & catch block  or try or finally block ten only we can able to handle Exception.To better understanding refer below example.

public class Throw_Multiple_Exception extends Exception
{
	public static void main(String args[])
	{
		String s1=args[0];
		String s2=args[1];
		int x=Integer.parseInt(s1);
		int y=Integer.parseInt(s2);
		int z;
		try
		{
			z=x/y;
			System.out.println(z);
		}
		/*catch(Exception e)
		{
			System.out.println(e);
		}*/
		/*finally
		{
			System.out.println("I am from Finally");
		}*/
	}
}

OUTPUT

E:\java>java Throw_Multiple_Exception 12 0 
                                 java.lang.ArithmeticException: / by zero 
E:\java>javac Throw_Multiple_Exception.java 
E:\java>java Throw_Multiple_Exception 12 0 
I am from Finally 
Exception in thread "main" java.lang.ArithmeticException: / by zero 
       at Throw_Multiple_Exception.main(Throw_Multiple_Exception.java:13) 
E:\java>javac Throw_Multiple_Exception.java Throw_Multiple_Exception.java:10: error: 'try' without 'catch', 'finally' or resource declarations 
            try ^ 1 error 
E:\java>

In the above example, we can see at last compilation, I didn’t use any combination with the try block and we got an error as “Throw_Multiple_Exception.java:10: error: ‘try’ without ‘catch’, ‘finally’ or resource declarations”.

Admin
We are group of application developer and admin.We are providing good content of information about IT technology and services .

Leave a Reply

Your email address will not be published. Required fields are marked *