An exception is any problem that occurs during the execution of a program and disrupts the normal flow of the programs instructions.In basic terms, when a condition occurs, in which it is not sure how to proceed in an ordinary way it creates an exception and forwards it to the runtime system to find an appropriate handler for the exception. In case, the runtime system is not able find an appropriate handler in the call hierarchy the runtime system terminates.
An exception can occur for many different reasons, below given are some scenarios where exception occurs.
- When a user enters a invalid data.
- When a file is not found that needs to be opened.
- When a network connection is lost
during the communications or
the JVM has run out of memory.
A custom - exception or user defined exception is an exception that you create for your ownself. Java custom exceptions are used to customize the exception according to user need. With the help of custom exception, we can create our own exception and message.
package com.myjava.exceptions;
public class MyException {
public static void main(String[] a){
try {
MyException.Test(null);
} catch(MyApException mae)
{
System.out.println("Inside catch block: "+mae.getMessage());
}
}
static void Test(String str) throws MyAppException{
if(str == null){
throw new MyAppException("String val is null");
}
}
}
class MyAppException extends Exception {
private String message = null;
public MyAppException() {
super();
}
public MyAppException(String message) {
super(message);
this.message = message;
}
public MyAppException(Throwable cause) {
super(cause);
}
public String toString() {
return message;
}
public String getMessage() {
return message;
} }
0 Comment(s)