Java Exceptions Tutorial
Exceptions in Java - Notes
Table of Contents
Types of Exceptions
A program without Exception
A program with try-catch
One try and multiple catch blocks
Nested try-catch
Use of printStackTraceMethod
User Defined Exceptions
Practice Quesstions on Java Exceptions
Introduction
Basically, errors are two types in programming development.
- Syntactical errors (Grammatical errors) occurs at compile time.
- Semantic errors (Logical errors) occurs at runtime.
What is an Exception?
Exception is nothing but a runtime error. Handling exception is called Exception
Handling
Exception is a some abnormal condition that occur during the execution of
the program.
Exception handler traps the runtime errors and makes the program execute
smoothly and completely without any interruption.
Exception superclass is ------ Throwable. It is available in java.lang package.
Throwable again subdivided into 2 classes
1. Error Class – These are hardware related errors. Also called as unchecked Exception can't be handled by code. Ex. Memory corrupted, Data corrupted, file not found, connection not established…etc. thrown by JVM.
2. Exception Class – It is checked exception can be handled. Thrown by java API, i.e., thrown by code.
Types of Exceptions in Java
- ArithmaticException - Occurs when a number is divided by zero Ex: result = 4/0;
- NumberFormatException - Occurs if you enter a Char in place of Number
- NullPointerException - when trying to read value from null variable
- ArrayIndexOutofBoundsException - where there are no sufficient elements in an array
- ClassNotFoundException - when you are trying to access a class that is not available
- IllegalAccessException - when there is no access permission to a file.
- InterruptedException - when a running application is interrupted, it usually occurs in threads.
- NoSuchMethodException - when you're trying to access the method that is not available
- IlligalArgumentException - when the passed argument is not matched.
To handle Exceptions there are 5 keywords are available in Java.
1. try2. catch
3. finally
4. throw
5. throws
Error possibility code is enclosed in try..catch block.
Exception Handling in Java.
syn:
try{
.....
.....
}catch(<Exception> e)
{
sop(e);
}
.....
A program without Exception
ex1:
public class Expdemo{
public static void main(String args[]){
int d=0;
int a=24/d;
System.out.println(a);
}
}
Result:
C:\Exceptions>java Expdemo
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Exp.main(Exp.java:4)
ex2:
A program using try..catch
Using try...catch, Handling runtime errors
public class Expdemo1{ public static void main(String args[]){ int num; int d=0; try{ num = 24/d; System.out.println("This is not printer"); } catch(ArithmeticException ae) { System.out.println("Divide by Zero"); } System.out.println("After the try...catch"); } }
Result
C:\Exceptions>java java Expdemo1
Divide by Zero
After the try...catch
finally
-- finally block follows the catch block finally block contains the code for releasing resource at the end of the program. Ex. closing an opened file or closing a database connection etc.
-- whether an exception raised or not finally must be executed.
syn:
try{
....
....
}
catch(Exp1 e1)
{ sop(e1);}
finally
{
cleanup;
}
ex: --- public class Finallydemo{ public static void main(String args[]){ int num; int d=0; try{ num = 24/d; System.out.println("This is not printer"); } catch(ArithmeticException ae) { System.out.println("Divide by Zero"); } finally { System.out.println("End of the program"); } } }
Result:
C:\Exceptions>java Finallydemo
Divide by Zero
End of the program
One try and multiple catch blocks
try{
....
....
}
catch(Exp1 e1)
{ sop(e1);}
catch(Exp2 e2)
{ sop(e1);}
public class Multicatchdemo { public static void main(String args[]){ int x; int y; int z; try{ x=15; y=Integer.parseInt(args[0]); z=x/y; System.out.println("z="+z);
catch(NumberFormatException ne)
{
System.out.println("Not a Number!!");
}
catch(ArithmeticException ae)
{
System.out.println("Divide by Zero");
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("Missing Argument..!!");
}
}
}
Result:
C:\Exceptions>java Multicatchdemo
java.lang.ArrayIndexOutOfBoundsException: 0Missing Argument..!!
C:\Exceptions>java Multicatchdemo j
java.lang.NumberFormatException: For input string: "j"
C:\Exceptions>java Multicatchdemo 2
z=7
In multi catch we should maintain the hierarchy means subclass
exceptions should come first, and its super class is next to that.
In
the following programs first Exception is declared next all child class
exceptions are declared like Numberformat, Arithmetic, ArrayIndex..etc…
These all errors handled by Exception. So JVM ignores and gives
unreacted exceptions' error.
So first subclass exceptions and if
any other exceptions raise which is not matched with subclass, then exception take care of them. Because it is the super class of all
exceptions.
ex: public class Multicatchdemo { public static void main(String args[]){ int x; int y; int z; try{ x=15; y=Integer.parseInt(args[0]); z=x/y; System.out.println("z="+z); } catch(Exception e) { System.out.println("Error in a program!!"); } catch(NumberFormatException ne) { System.out.println("Not a Number!!"); } catch(ArithmeticException ae) { System.out.println("Divide by Zero"); } catch(ArrayIndexOutOfBoundsException ae) { System.out.println("Missing Argument..!!");} } }
Result: Compilation Error
C:\Exceptions>javac Multicatchdemo.java
Multicatch1.java:17: error: exception NumberFormatException has already been caught
catch(NumberFormatException ne)
^
Multicatch1.java:21: error: exception ArithmeticException has already been caught
catch(ArithmeticException ae)
^
Multicatch1.java:25: error: exception ArrayIndexOutOfBoundsException has already been caught
catch(ArrayIndexOutOfBoundsException ae)
^
3 errors
The Exception catch block must have written as a last catch
The above code should be modified as shown below
ex:
public class Multicatchdemo
{
public static void main(String args[]){
int x;
int y;
int z;
try{
x=15;
y=Integer.parseInt(args[0]);
z=x/y;
System.out.println("z="+z);
}
catch(NumberFormatException ne)
{
System.out.println("Not a Number!!");
}
catch(ArithmeticException ae)
{
System.out.println("Divide by Zero");
}
catch(ArrayIndexOutOfBoundsException ae)
{ System.out.println("Missing Argument..!!");}
catch(Exception e)
{
System.out.println("Error in a program!!");
} }
}
Result: No compilation error
output:
C:\Exceptions>javac Multicatch1.java
C:\Exceptions>java Multicatch1
Missing Argument..!!
C:\Exceptions>java Multicatch1 j
Not a Number!!
C:\Exceptions>java Multicatch1 2
z=7
C:\Exceptions>
public class Aiobdemo{ public static void main(String args[]){ int a[]={10, 20, 30, 40, 50, 60 }; try{ for(int i=0;i<=a.length;i++) System.out.println(a[i]); } catch(ArrayIndexOutOfBoundsException ae) { System.out.println("insufficient Array Size");} } }
Result:
C:\Exceptions>java Aiob
10
20
30
40
50
60
insufficient Array Size
Nested try..catch
One try..catch, inside another try...catch block
(just like nested while, nested for..etc)
try{
| ....
| ....
|
|----- ----try{
| | ....
| | ....
| |
| |
| ----catch(Exp1 e1)
| { sop(e1);}
|
|
| }
----catch(Exp2 e2)
{ sop(e1);}
Ex:
public class Nestedcatch
{
public static void main(String args[]){
int a;
int b;
int c;
a=15;
try{
b=Integer.parseInt(args[0]);
try{
c=a/b;
System.out.println("c="+c);
}
catch(ArithmeticException ae)
{
System.out.println("Divide by Zero");
}
}
catch(NumberFormatException e)
{ System.out.println("Not a Number..!!");
}
}
}
throw
Throwing an exception to caller. So caller will handle that exception, i.e., that method should be called in try...catch block.
Use of printStackTraceMethod()
This is method is declared in Throwable class. Traces the error where exactly it originated. by displaying the line no.
public class ThrowDemo
{
static void m1()
{
try{
throw new NullPointerException("Demo");
}
catch(NullPointerException ne)
{
System.out.println("Caught in m1()");
throw ne;
}
}
public static void main(String args[]){
ThrowDemo td = ThrowDemo();
try{
tc.m1();
}
catch(NullPointerException ne){
System.out.println("Re caught in main()");
}
}}
Result:
C:\Exceptions>java ThrowDemo
Caught in m1()
Re caught in main()
throws
The method will declared as it throws an Exception. that should be catched by caller.
Syn:
public void m1() throws NumberFormatException
{
....
....
}
while calling the methods should be enclosed in try...catch block and should be catched throwing exception
if it is called in main...it should in try...catch()
try{
m1();
catch(NumberFormatException ne)
{
s.o.p(ne);
}
User defined Exceptions in Java
***place both files in same file and save as MyExpTest.java
public class MyException extends Exception {
public MyException() {
}
public MyException(String msg) {
super(msg);
}
}
public class MyExpDemo {
public static void arraySize(int size)throws MyException {
if(size<0)
throw new MyException("Negative size");
// System.out.println("size="+size);
}
public static void main(String[] args) {
MyExpDemo me= new MyExpDemo();
try {
me.arraySize(-5);
} catch (MyException e) {
e.printStackTrace();
}
}
}
Result:
C:\Exceptions>java MyExpDemo
MyException: Negative size
at MyExpTest.arraySize(MyExpTest.java:17)
at MyExpTest.main(MyExpTest.java:26)
Comments
Post a Comment