java custom exception

java custom exception :

To create custom exception in java just extends Exception class.

Example :


package com.pkjavacode.com;

class MyException1 extends Exception {
private String message;

public MyException1(String message) {

this.message = message;
}

public String getMessage() {
return message;
}
}

public class MyException {
public static void main(String[] a) {
try {
MyException.myTest(null);
} catch (MyException1 mae) {
System.out.println("Inside catch block: " + mae.getMessage());
}
}

static void myTest(String str) throws MyException1 {
if (str == null) {
throw new MyException1("String val is null");
}
}
}

 

Output :
Inside catch block: String val is null

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s