Exception handling
------------------
Exception is a runtime error which terminates a program abnormally.
Errors
------
It is a deviation in a program.
There are 3 types of errors
i)compiletime/syntax errors.
ii)Runtime errors.
iii)logical errors.
compile time errors
-------------------
Errors raised due to wrong syntax.
ex:
semicolon missing;
undefined symbol a
etc
Runtime error
-------------
A runtime error causes a program to terminate abnormally at the time of executing a program.
ex:
ArrayIndexOutOfBoundsException.
ArithmeticException.
Runtime errors is also called as Exceptions.
logical errors
--------------
It causes to get wrong output.
Program
-------
class Test
{
public static void main(String args[])
{
int a=10,b=0,c;
c=a/b;//line1
System.out.println(c);
System.out.println("The end");
}
}
The above program raises runtime error @line1, because we are trying to divide a number by zero
saying
Exception in thread "main" java.lang.ArithmeticException: / by z
at Test.main(Test.java:6).
An Exception is raised because of a risky statement in a program.
In the abovne code
c=a/b; is a risky statement.
A risky statement may raise exception but we can't guarantee that exception is always raised because of risky statement it depends on input provided by user.
Exception Handling
------------------
It is a mechanism which avoids abnormal termination of a program.
we implement execption handling using the following keywords
i)try
ii)catch
iii)finally
iv)throws
v)throw
try
---
A try block consists of risky statements.
Whenever an execption is raised in try block then it is thrown to catch block.
syntax
------
try
{
//risky statements
}
catch
-----
A catch block catches the exception thrown from try block.
A catch catches the exception thrown from try block and avoids abnormal termination of a program
Here catch is handling the exception so catch block is called as EXception handler.
syntax
------
catch(ExceptionType reference)
{
//statements
}
we can handle exception by using try/catch block.
syntax
------
try
{
//risky statements
}
catch(ExceptionType reference)
{
}
Program
-------
class Test
{
public static void main(String args[])
{
int a=10,b=0,c;
try
{
c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
}
System.out.println("The end");
}
}
Execution flow of try/catch
---------------------------
A catch block is executed only if an execption is raised in a try block otherwise a catch block is never executed.
finally
-------
A finally block is used to perform cleanup operations.
A finally block can be declared after try block or catch block.
syntax
------
try
{
}
catch()
{
}
finally
{
}
or
try
{
}
finally
{
}
Cleanup operations means closing connections like
closing file connections.
database connections.
network connections.
Program
-------
import java.util.Scanner;
import java.util.InputMismatchException;
class Test
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter a");
try
{
int a=s.nextInt();
System.out.println(" a"+a);
}
catch(InputMismatchException e)
{
System.out.println(e);
}
finally
{
s.close();
}
System.out.println("The end");
}
}
Excecution flow try/catch/finally
---------------------------------
A try block is always executed.
A catch block is executed only when execption is raised in try block.
A finally block is always executed irrespective of exception.
A try block must be declared with a catch block or finally block.
which of the following declarations are valid?
i)try
{
}
catch()
{
}
ii)try
{
}
catch()
{
}
finally
{
}
iii)
try
{
}
finally
{
}
iv)try
{
}
v)catch()
{
}
Exception Heirarchy
-------------------
Object
^
|
Throwable
^ ^
| |
Exception Error
| |
IOException RuntimeException StackOverFlow
ServletException | |Error
etc ArithemeticException |Assertion
ArrayIndexOutOfBounds|Error
Exception
NullPointerException
etc
Object is the super class of all classes in java.
Throwable is the super class of Exception and Error.
Exception is used to handle programmatic issues.
Error is used to handle system issues.
Types of exceptions
-------------------
Exceptions are of 2 types
i)checked
ii)Unchecked
checked
-------
Exceptions which are checked by compiler are called checked exceptions.
Exception is always raised at runtime but compiler will raise an error if there any possibility of Exception at runtime such type of exceptions are checked exceptions.
Exceptions like IOException,ServletException etc are checked exceptions.
Unchecked
---------
Exceptions which are checked by jvm and not checked by compiler are called unchecked exceptions.
RuntimeException and its subclasses and Error and its subclasses are unchecked exceptions and remaining are checked exceptions
Exception and Throwable are partially checked exceptions because they has both checked and unchecked classes as subclasses.
Note:Majority of Exception classes are available in java.lang.* package.
throws
------
throws is used to throw or delegate an exeception from a method.
throws is used to throw only checked exceptions.
syntax
------
accessmodifier returntype methodname() throws ExceptionType
{
}
Program to demonstrate handling checked exception IOException
-------------------------------------------------------------
Program
-------
import java.io.*;
class Test
{
public static void main(String args[]) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
String name=dis.readLine();
System.out.println(name);
}
}
DataInputStream is a class available in java.io.*;
readLine() is used to input value from keyboard.
readLine() method throws checked exeception,IOException.
we can handle a checked exeception in 2 ways
i)Using try/catch
ii)using throws keyword.
In the above code we are hadling IOException using throws,here we are simply forwarding(delegating) exception to jvm but we are not handling exception,it is jvm which handles exeception here.
Note:if we want to handle exception explicitly in the code itself then we should use try/catch block.
try with mutiple catches
------------------------
we can declare a try block with mutiple catch clocks.
if we declare muiptle risky statements in try block,to handle this multiple exceptions thrown from try we can use multiple catch blocks.
syntax
-----
try
{
//risky statement1
//risky statement2
.
.
}
catch(ExceptionType1 reference)
{
}
catch(ExceptionType2 reference)
{
}
.
.
.
program to handle AE and AIOOBE using try with multiple catches
---------------------------------------------------------------
import java.io.*;
class Test
{
public static void main(String args[])
{
int a=10,b=0,c;
int x[]={1,2,3,4,5};
try{
c=a/b;//line1
System.out.println(c);
System.out.println(x[6]);//line2
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("Byee");
}
}
In the above code we are declaring 2 risky statements @line1,@line2
@line1 may raise ArithemeticException.
@line2 may raise ArrayIndexOutOfBoundsException
to handle both the exceptions we are declaring catch blocks,one with ArithemeticException and the other with ArrayIndexOutOfBoundsException.
If exception is raised @line1 then its corresponding catch block with ArithmeticException is executed .
If exception is raised @line2 then its corresponding catch block with ArrayIndexOutOfBoundsException is executed.
A catch block handling all the exceptions
-----------------------------------------
A cathc block can handle any exception thrown by try block if we declare the parameter of catch as super class i,e
if we declare "Throwable" class as a parameter it can handle any exception/error thrown from try block.
syntax
------
try
{
}
catch(Throwable e)
{
}
if we declare "Exception" as a parameter it can handle any exception thrown from try block but it cannot handle errors
syntax
------
try
{
}
catch(Exception e)
{
}
if we declare "Error" as a parameter it can handle any error thrown from try block but it cannot handle exceptions.
syntax
------
try
{
}
catch(Error e)
{
}
Program to handle mutiple exceptions using a catch block
--------------------------------------------------------
//what is the output of the following code?
class CatchTest
{
public static void main(String args[])
{
int a=10,b=0,c;
int x[]={1,2,3,4,5};
try
{
c=a/b;
System.out.println(c);
System.out.println(x[4]);
}
catch(Exception e)
{
System.out.println(e);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}
/*options
-------
i)CE
ii)RE
iii)compiles successfully
iv)compiles and executes*/
Reason
------
In the above code we get compilation error because the catch block with exception as parameter will handle all the excetions thrown from try block,and other catch blocks never get a chance for execution.
so we get a compilation error saying
"Exception ArithmeticException has already been caught"
same for ArrayIndexOutOfBoundsException.
Note:
Whenever we are declaring mutiple catch blocks,always declare parameters to catch blocks from sub class to super calss i,e declare a catch block with subclass as parameter first and then declare a catch block with its super class as as a parameter.
Rewriting above program to fix compilaion error
------------------------------------------------
class CatchTest
{
public static void main(String args[])
{
int a=10,b=0,c;
int x[]={1,2,3,4,5};
try
{
c=a/b;
System.out.println(c);
System.out.println(x[4]);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Here catch with subclasses as parameter is declared first and catch block with a superclass[Exception] is kept last in the heirarchy.
UserDefined exceptions
----------------------
Exceptions are of 2 types
i)Built-in exceptions
ii)Userdefined
Built-in are predefined or existing exceptions.
NullPointerException.
ArithmeticException.
etc
Exceptions developed by developer are called userdefined exceptions.
We can create our own exceptions by extending a class from built-in exception.
The nature of userdefined exception depends on the kind of super class it is extending.
steps for creating userdefined exceptions
-----------------------------------------
step1:extend a class from a built-in exception like Exception\Throwable\Error\RuntimeException etc depends on requirement.
accessmodifier class ClassName extends Exception
{
}
step2:declare a parameterized constructor with String as a parameter.
accessmodifier class ClassName extends Exception
{
accessmodifier ClassName(String msg)
{
}
}
step3:Declare super() in the contructor and deligate the String parameter to super class constructor.
accessmodifier class ClassName extends Exception
{
accessmodifier ClassName(String msg)
{
super(msg);
}
}
throw
-----
A throw keyword is used to throw an exception from a try block to catch block programatically or explicitly.
we can throw both built-in and userdefined exceptions using throw keyword but it is recommended to use throw keyword to throw userdefined exceptions because predefined exceptions are automatically thrown from try block catch block by jvm.
syntax
------
throw new ExceptionType(args);
ex:
throw new ArithmeticException("Division by zero");
throw new InvalidSalaryException("Incorrect Amount");
Program to demonstrate userdefined exception
--------------------------------------------
//create a Exception InsufficientFundsException
package com.manohar.java.exceptions;
public class InsufficientFundsException extends Exception{
public InsufficientFundsException(String msg){
super(msg);
}
}
//create a BalTest.java to test exception
---------------------------------------
package com.manohar.java.test;
import java.util.Scanner;
import com.manohar.java.exceptions.InsufficientFundsException;
public class BalTest {
public static void main(String[] args) {
// declaring variables
double bal = 10000.00;
double amount;
// creating scanner
Scanner s = new Scanner(System.in);
System.out.println("Enter amount");
amount = s.nextDouble();
if (amount > bal) {
try {
throw new InsufficientFundsException("Please enter proper amount");
}
catch (InsufficientFundsException e) {
System.out.println(e);
}
}
else{
System.out.println("Amount withdrwn "+amount);
System.out.println("Ramaining bal "+(bal-amount));
}
}
}
Displaying Exception Summary
----------------------------
Exception summary can be displayed 3 ways.
i)Printing reference of Exception.
ii)getMessage().
iii)printStackTrace().
i)Printing reference
This approach displays both exception and message
System.out.println(e):
ii)getMessage()
This approach displays only message
System.out.println(e.getMessage());
iii)printStackTrace()
This method display complete summary of exception
e.printStackTrace();
Program
-------
class Test
{
public static void main(String args[])
{
int a=10,b=0,c;
try
{
c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();
}
}
}
output
------
/ by zero//getMessgae()
java.lang.ArithmeticException: / by zero//printing reference
java.lang.ArithmeticException: / by zero//stack Trace
at Test.main(Test.java:8)
catch with multiple parameters
------------------------------
We can declare multiple paramters with a catch block from 1.7 version onwards.
syntax
------
try
{
//statements
}
catch(ExceptionType1|ExceptionType2|... reference)
{
}
Program
-------
class Test
{
public static void main(String args[])
{
int a=10,b=10,c;
int x[]={1,2,3,4,5};
try
{
c=a/b;
System.out.println(c);
System.out.println(x[6]);
}
catch(ArithmeticException|ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
}
}
try with resources
------------------
Generally we use finally block to perform clean up operations but by using try with resources we dont need to use finally block because closing connections is automatically done by using try with resources.
syntax
------
try(rerefence type)
{
}
catch(ExceptionType e)
{
}
Program
-------
import java.util.*;
class Test
{
public static void main(String args[])
{
try(Scanner s=new Scanner(System.in))
{
System.out.println("Enter a");
int a=s.nextInt();
System.out.println(a);
}
catch(InputMismatchException e)
{
e.printStackTrace();
}
System.out.println("The end");
}
}
try with resources reduces length of the code because it avoids usage of finally block.
Nested try/catch block
----------------------
A try/catch block within try or catch or finally blocks is known as nested try catch
syntax
------
try
{
try{
//
}
catch(ExceptionType e)
{
}
}
catch(ExceptionType e)
{
try{
//
}
catch(ExceptionType e)
{
}
}
finally
{
try{
//
}
catch(ExceptionType e)
{
}
}
throw throws
----- ------
throws exception throws exception from a method
from a try block
programmatically
used to userdefined used to throw checked exceptions
exceptions
syntax syntax
------ --------
throw new ExceptionType(""); accessmodifier returntype methodname() throws ExceptionType
{
//
}
------------------
Exception is a runtime error which terminates a program abnormally.
Errors
------
It is a deviation in a program.
There are 3 types of errors
i)compiletime/syntax errors.
ii)Runtime errors.
iii)logical errors.
compile time errors
-------------------
Errors raised due to wrong syntax.
ex:
semicolon missing;
undefined symbol a
etc
Runtime error
-------------
A runtime error causes a program to terminate abnormally at the time of executing a program.
ex:
ArrayIndexOutOfBoundsException.
ArithmeticException.
Runtime errors is also called as Exceptions.
logical errors
--------------
It causes to get wrong output.
Program
-------
class Test
{
public static void main(String args[])
{
int a=10,b=0,c;
c=a/b;//line1
System.out.println(c);
System.out.println("The end");
}
}
The above program raises runtime error @line1, because we are trying to divide a number by zero
saying
Exception in thread "main" java.lang.ArithmeticException: / by z
at Test.main(Test.java:6).
An Exception is raised because of a risky statement in a program.
In the abovne code
c=a/b; is a risky statement.
A risky statement may raise exception but we can't guarantee that exception is always raised because of risky statement it depends on input provided by user.
Exception Handling
------------------
It is a mechanism which avoids abnormal termination of a program.
we implement execption handling using the following keywords
i)try
ii)catch
iii)finally
iv)throws
v)throw
try
---
A try block consists of risky statements.
Whenever an execption is raised in try block then it is thrown to catch block.
syntax
------
try
{
//risky statements
}
catch
-----
A catch block catches the exception thrown from try block.
A catch catches the exception thrown from try block and avoids abnormal termination of a program
Here catch is handling the exception so catch block is called as EXception handler.
syntax
------
catch(ExceptionType reference)
{
//statements
}
we can handle exception by using try/catch block.
syntax
------
try
{
//risky statements
}
catch(ExceptionType reference)
{
}
Program
-------
class Test
{
public static void main(String args[])
{
int a=10,b=0,c;
try
{
c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
}
System.out.println("The end");
}
}
Execution flow of try/catch
---------------------------
A catch block is executed only if an execption is raised in a try block otherwise a catch block is never executed.
finally
-------
A finally block is used to perform cleanup operations.
A finally block can be declared after try block or catch block.
syntax
------
try
{
}
catch()
{
}
finally
{
}
or
try
{
}
finally
{
}
Cleanup operations means closing connections like
closing file connections.
database connections.
network connections.
Program
-------
import java.util.Scanner;
import java.util.InputMismatchException;
class Test
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter a");
try
{
int a=s.nextInt();
System.out.println(" a"+a);
}
catch(InputMismatchException e)
{
System.out.println(e);
}
finally
{
s.close();
}
System.out.println("The end");
}
}
Excecution flow try/catch/finally
---------------------------------
A try block is always executed.
A catch block is executed only when execption is raised in try block.
A finally block is always executed irrespective of exception.
A try block must be declared with a catch block or finally block.
which of the following declarations are valid?
i)try
{
}
catch()
{
}
ii)try
{
}
catch()
{
}
finally
{
}
iii)
try
{
}
finally
{
}
iv)try
{
}
v)catch()
{
}
Exception Heirarchy
-------------------
Object
^
|
Throwable
^ ^
| |
Exception Error
| |
IOException RuntimeException StackOverFlow
ServletException | |Error
etc ArithemeticException |Assertion
ArrayIndexOutOfBounds|Error
Exception
NullPointerException
etc
Object is the super class of all classes in java.
Throwable is the super class of Exception and Error.
Exception is used to handle programmatic issues.
Error is used to handle system issues.
Types of exceptions
-------------------
Exceptions are of 2 types
i)checked
ii)Unchecked
checked
-------
Exceptions which are checked by compiler are called checked exceptions.
Exception is always raised at runtime but compiler will raise an error if there any possibility of Exception at runtime such type of exceptions are checked exceptions.
Exceptions like IOException,ServletException etc are checked exceptions.
Unchecked
---------
Exceptions which are checked by jvm and not checked by compiler are called unchecked exceptions.
RuntimeException and its subclasses and Error and its subclasses are unchecked exceptions and remaining are checked exceptions
Exception and Throwable are partially checked exceptions because they has both checked and unchecked classes as subclasses.
Note:Majority of Exception classes are available in java.lang.* package.
throws
------
throws is used to throw or delegate an exeception from a method.
throws is used to throw only checked exceptions.
syntax
------
accessmodifier returntype methodname() throws ExceptionType
{
}
Program to demonstrate handling checked exception IOException
-------------------------------------------------------------
Program
-------
import java.io.*;
class Test
{
public static void main(String args[]) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
String name=dis.readLine();
System.out.println(name);
}
}
DataInputStream is a class available in java.io.*;
readLine() is used to input value from keyboard.
readLine() method throws checked exeception,IOException.
we can handle a checked exeception in 2 ways
i)Using try/catch
ii)using throws keyword.
In the above code we are hadling IOException using throws,here we are simply forwarding(delegating) exception to jvm but we are not handling exception,it is jvm which handles exeception here.
Note:if we want to handle exception explicitly in the code itself then we should use try/catch block.
try with mutiple catches
------------------------
we can declare a try block with mutiple catch clocks.
if we declare muiptle risky statements in try block,to handle this multiple exceptions thrown from try we can use multiple catch blocks.
syntax
-----
try
{
//risky statement1
//risky statement2
.
.
}
catch(ExceptionType1 reference)
{
}
catch(ExceptionType2 reference)
{
}
.
.
.
program to handle AE and AIOOBE using try with multiple catches
---------------------------------------------------------------
import java.io.*;
class Test
{
public static void main(String args[])
{
int a=10,b=0,c;
int x[]={1,2,3,4,5};
try{
c=a/b;//line1
System.out.println(c);
System.out.println(x[6]);//line2
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("Byee");
}
}
In the above code we are declaring 2 risky statements @line1,@line2
@line1 may raise ArithemeticException.
@line2 may raise ArrayIndexOutOfBoundsException
to handle both the exceptions we are declaring catch blocks,one with ArithemeticException and the other with ArrayIndexOutOfBoundsException.
If exception is raised @line1 then its corresponding catch block with ArithmeticException is executed .
If exception is raised @line2 then its corresponding catch block with ArrayIndexOutOfBoundsException is executed.
A catch block handling all the exceptions
-----------------------------------------
A cathc block can handle any exception thrown by try block if we declare the parameter of catch as super class i,e
if we declare "Throwable" class as a parameter it can handle any exception/error thrown from try block.
syntax
------
try
{
}
catch(Throwable e)
{
}
if we declare "Exception" as a parameter it can handle any exception thrown from try block but it cannot handle errors
syntax
------
try
{
}
catch(Exception e)
{
}
if we declare "Error" as a parameter it can handle any error thrown from try block but it cannot handle exceptions.
syntax
------
try
{
}
catch(Error e)
{
}
Program to handle mutiple exceptions using a catch block
--------------------------------------------------------
//what is the output of the following code?
class CatchTest
{
public static void main(String args[])
{
int a=10,b=0,c;
int x[]={1,2,3,4,5};
try
{
c=a/b;
System.out.println(c);
System.out.println(x[4]);
}
catch(Exception e)
{
System.out.println(e);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}
/*options
-------
i)CE
ii)RE
iii)compiles successfully
iv)compiles and executes*/
Reason
------
In the above code we get compilation error because the catch block with exception as parameter will handle all the excetions thrown from try block,and other catch blocks never get a chance for execution.
so we get a compilation error saying
"Exception ArithmeticException has already been caught"
same for ArrayIndexOutOfBoundsException.
Note:
Whenever we are declaring mutiple catch blocks,always declare parameters to catch blocks from sub class to super calss i,e declare a catch block with subclass as parameter first and then declare a catch block with its super class as as a parameter.
Rewriting above program to fix compilaion error
------------------------------------------------
class CatchTest
{
public static void main(String args[])
{
int a=10,b=0,c;
int x[]={1,2,3,4,5};
try
{
c=a/b;
System.out.println(c);
System.out.println(x[4]);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Here catch with subclasses as parameter is declared first and catch block with a superclass[Exception] is kept last in the heirarchy.
UserDefined exceptions
----------------------
Exceptions are of 2 types
i)Built-in exceptions
ii)Userdefined
Built-in are predefined or existing exceptions.
NullPointerException.
ArithmeticException.
etc
Exceptions developed by developer are called userdefined exceptions.
We can create our own exceptions by extending a class from built-in exception.
The nature of userdefined exception depends on the kind of super class it is extending.
steps for creating userdefined exceptions
-----------------------------------------
step1:extend a class from a built-in exception like Exception\Throwable\Error\RuntimeException etc depends on requirement.
accessmodifier class ClassName extends Exception
{
}
step2:declare a parameterized constructor with String as a parameter.
accessmodifier class ClassName extends Exception
{
accessmodifier ClassName(String msg)
{
}
}
step3:Declare super() in the contructor and deligate the String parameter to super class constructor.
accessmodifier class ClassName extends Exception
{
accessmodifier ClassName(String msg)
{
super(msg);
}
}
throw
-----
A throw keyword is used to throw an exception from a try block to catch block programatically or explicitly.
we can throw both built-in and userdefined exceptions using throw keyword but it is recommended to use throw keyword to throw userdefined exceptions because predefined exceptions are automatically thrown from try block catch block by jvm.
syntax
------
throw new ExceptionType(args);
ex:
throw new ArithmeticException("Division by zero");
throw new InvalidSalaryException("Incorrect Amount");
Program to demonstrate userdefined exception
--------------------------------------------
//create a Exception InsufficientFundsException
package com.manohar.java.exceptions;
public class InsufficientFundsException extends Exception{
public InsufficientFundsException(String msg){
super(msg);
}
}
//create a BalTest.java to test exception
---------------------------------------
package com.manohar.java.test;
import java.util.Scanner;
import com.manohar.java.exceptions.InsufficientFundsException;
public class BalTest {
public static void main(String[] args) {
// declaring variables
double bal = 10000.00;
double amount;
// creating scanner
Scanner s = new Scanner(System.in);
System.out.println("Enter amount");
amount = s.nextDouble();
if (amount > bal) {
try {
throw new InsufficientFundsException("Please enter proper amount");
}
catch (InsufficientFundsException e) {
System.out.println(e);
}
}
else{
System.out.println("Amount withdrwn "+amount);
System.out.println("Ramaining bal "+(bal-amount));
}
}
}
Displaying Exception Summary
----------------------------
Exception summary can be displayed 3 ways.
i)Printing reference of Exception.
ii)getMessage().
iii)printStackTrace().
i)Printing reference
This approach displays both exception and message
System.out.println(e):
ii)getMessage()
This approach displays only message
System.out.println(e.getMessage());
iii)printStackTrace()
This method display complete summary of exception
e.printStackTrace();
Program
-------
class Test
{
public static void main(String args[])
{
int a=10,b=0,c;
try
{
c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();
}
}
}
output
------
/ by zero//getMessgae()
java.lang.ArithmeticException: / by zero//printing reference
java.lang.ArithmeticException: / by zero//stack Trace
at Test.main(Test.java:8)
catch with multiple parameters
------------------------------
We can declare multiple paramters with a catch block from 1.7 version onwards.
syntax
------
try
{
//statements
}
catch(ExceptionType1|ExceptionType2|... reference)
{
}
Program
-------
class Test
{
public static void main(String args[])
{
int a=10,b=10,c;
int x[]={1,2,3,4,5};
try
{
c=a/b;
System.out.println(c);
System.out.println(x[6]);
}
catch(ArithmeticException|ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
}
}
try with resources
------------------
Generally we use finally block to perform clean up operations but by using try with resources we dont need to use finally block because closing connections is automatically done by using try with resources.
syntax
------
try(rerefence type)
{
}
catch(ExceptionType e)
{
}
Program
-------
import java.util.*;
class Test
{
public static void main(String args[])
{
try(Scanner s=new Scanner(System.in))
{
System.out.println("Enter a");
int a=s.nextInt();
System.out.println(a);
}
catch(InputMismatchException e)
{
e.printStackTrace();
}
System.out.println("The end");
}
}
try with resources reduces length of the code because it avoids usage of finally block.
Nested try/catch block
----------------------
A try/catch block within try or catch or finally blocks is known as nested try catch
syntax
------
try
{
try{
//
}
catch(ExceptionType e)
{
}
}
catch(ExceptionType e)
{
try{
//
}
catch(ExceptionType e)
{
}
}
finally
{
try{
//
}
catch(ExceptionType e)
{
}
}
throw throws
----- ------
throws exception throws exception from a method
from a try block
programmatically
used to userdefined used to throw checked exceptions
exceptions
syntax syntax
------ --------
throw new ExceptionType(""); accessmodifier returntype methodname() throws ExceptionType
{
//
}
No comments:
Post a Comment