Friday, 7 August 2015

Writing your own custom exception in Java

1. Custom defined exception in Java


package exception.custom;

public class MyException extends Exception {

public MyException(String message)
{
super(message);
}

}

Analysis of the above code

"MyException" is our exception class name. It can be any name.
Mandatory thing to be done is our class extends "Exception" class to provide exception feature to you class. 
"Now we define a constructor of my class. This constructer takes a "String" argument. We call super class' constructor(super class here is "Exception class") and pass this string to it. Now Java creates a new Exception with the message passed in the input String

2. How to make use of the custom defined exception

Using Try/Catch block

package exception.custom;

public class CustomException {

/**
* @param args
* @throws MyException 
*/
public static void main(String[] args) {
try{
for (int i = 0; i <10; i++) {
System.out.println(i);

if(i==5){
throw new MyException("My Exception Occurred");
}
}
}

catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Ouput:

0
1
2
3
4
5
exception.custom.MyException: My Exception Occurred
at exception.custom.CustomException.main(CustomException.java:15)

Using Throws

package exception.custom;

public class CustomException {

/**
* @param args
* @throws MyException 
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
for (int i = 0; i <=10; i++) {
System.out.println(i);
if(i==5){
throw new MyException("My Exception Occurred");
}
}
}
}

Ouput:

0
1
2
3
4
5
Exception in thread "main" exception.custom.MyException: My Exception Occurred
at exception.custom.CustomException.main(CustomException.java:16)

No comments:

Post a Comment