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