Java Interview Question Part - 4

Q1. What is an exception?
Ans : An exception is an abnormal event that come during the program execution and disrupts the normal flow of the program's instruction.

Q2. What is purpose of the throw and throws keyword in exception?
Ans : throws keyword is used to specify that a method may raise an exception during it's execution.It enforces explicity excepiton
exception handling when we call this method.

public void getLone() throws Exception{
}
throw keyword used in normal condition ,when object to interrupt the normal flow of the program.throw keyword is mostly commanly
used when a program fail to stisfy a given condition.

if(card.isFinalAmout()){
throw new FinalAmoutException("The Card amount is not complited");
}

Q3. What is difference between a checked and an unchecked exception?
Ans: Checked exception must be handled within a try-catch block or declared in a throws clause but uncheck exception is not required to handle not be declared.
All exception are checked exceptions, except those indicated by Error ,RuntimeException and their subclasses.
checked and unchecked exception also know as compile time and run time exception.

Q4.How to create custom exception?
Ans: Your class should extend class Exception or any of it's subclasses to create out custom  exception. Tis custom exception class can have it's own variable and methods
that we can use to pass error code or other exception related information to the exception handler.
let's see in bellow example:

import java.io.Exception;
public class AccountBalance extends IOException{
private static final long serialVersionUID = 4664459809499611218L;
private String errorCode="UnKnownException";
public AccountBalance (String message ,String errorCode){
   Super(message);
   this.errorCode = errorCode;
}
public String getErrorCode(){
return this.errorCode;
}
}

Q5. What is OutOfMemoryError in Java ?
Ans: In Java OutOfMemoryError is subclass of java.lang.vertualMachineError and it's throws by JVM, when it run out heap memory.
We can fix this error by providing more memory to run the java application.
Exp:

$>java <> -Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxPermSize=256m

No comments: