Exception Handling Keywords:
Java provides several keywords for exception handling. Let's first understand these keywords, and then we'll write a simple program to demonstrate how to use them for exception handling.
1. throw
We know that when an exception occurs, Java creates an exception object, and the Java runtime begins processing it to handle the exception. Sometimes, we may want to explicitly generate an exception in our code. For example, in a user authentication program, we should throw an exception if the password is null. The throw keyword is used to explicitly throw an exception, which is then handled by the Java runtime or propagated to the calling method.
2. throws
When a method throws an exception and does not handle it, you must use the throws keyword in the method signature to inform the caller about the exceptions that the method may throw. The calling method can either handle these exceptions using a
try-catch block or propagate them to its caller by declaring the throws keyword in its own method signature. You can specify multiple exceptions in the throws clause, and it can also be used with the main() method.3. try-catch
We use the try-catch block to handle exceptions in Java. The
try block contains the code that may throw an exception, while the catch block handles the exception if one occurs. A single try block can be followed by multiple catch blocks to handle different types of exceptions. Additionally, try-catch blocks can be nested. Each catch block requires a parameter whose type must be an exception class or one of its subclasses.4. finally
The
finally block is optional and is used with a try block, either with or without a catch block. Since an exception can interrupt the normal flow of program execution, some resources (such as files, database connections, or network sockets) may remain open if they are not closed properly. The finally block is typically used to release these resources. It is executed regardless of whether an exception occurs or not, ensuring that cleanup code always runs.Let's look at the following important points:
You cannot have a
catchorfinallyblock without a correspondingtryblock.A
trystatement must be followed by at least onecatchblock, afinallyblock, or both.You cannot write any code between the
try,catch, andfinallyblocks. Doing so results in a compile-time error. For example, you cannot place any statements between atryblock and its correspondingcatchblock.A single
tryblock can be followed by multiplecatchblocks to handle different types of exceptions.try-catchblocks can be nested, just likeif-elsestatements.A
trystatement can have only onefinallyblock.
Below some questions related to try catch and finally block examples.
1) Which is the base class of all Exception classes?
Throwable
2) Once the control switches to the catch block does it return back to the try block to execute the balance code?
No. Once the control jumps to the catch block it never returns to the try block but it goes to finally block(if present).
3) How do you get the descriptive information about the Exception occurred during the program execution?
All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred.
e.g catch(Exception e){
Systom.out.println(e.printStackTrace());
}
4)
try{
//some statements
}
catch(Exception e){
System.out.println("Exception ");
}
catch(ArithmeticExcetion ex){
System.out.println("AritmeticException ");
}
What is output?
This code will produce a compile-time error at the second
catch block. The Exception class is the superclass of all checked exceptions and most runtime (unchecked) exceptions, including ArithmeticException. Since ArithmeticException is a subclass of Exception, placing the Exception catch block before the ArithmeticException catch block makes the latter unreachable. Therefore, the Exception catch block should always be placed at the end of the catch block sequence.5) What will be the output of the following code?
try{
//some statements
} //line 1
System.out.println("end try block");
catch(Exception e){ //line 2
System.out.println("Exception ");
}
It will give compile-time error at line 1 and line 2 because for first line you haven't written catch or finally block & second it act as without try block.
6) What will be the output of the following code?
public int methodName(){
try{
//some statements
return 1;
}
catch(Exception e){
return 2;
}
finally{
return 3;
}
} //end method
The above method will return which value 1 or 2 or 3. also answer me with exception & without exception.
In java finally block will execute all time except calling System.exit(). So above example it will return always 3 with exception or non-exception(not a matter).
7) What will be the output of the following code?
try{
int i=0; int j=1;
int sum=j/i; //line 1
System.exit(0); //line 2
}
catch(Exception e){
e.printStackTrace();
}
finally{
System.out.println("finally block");
}
Output is----------------java.lang.ArithmeticException
finally block
In the above code,at line 1,it will throw exception i.e catch block will execute and followed by finaaly block execute. It never return to the line 2.
8) What will be the output of the following code?
try{
int sum=1/1; //line 1
System.out.println(sum);
System.exit(0); //line 2
}
catch(Exception e){
e.printStackTrace();
}
finally{
System.out.println("finally block");
}
In the above code finally block won't execute because it will exit in try block itself.
output is 1.
9) Exception Hierarchy in java
Error :
An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself.
Exception :
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. There are two types of Exceptions 1)Checked Exception 2) Unchecked Exception
1) Checked Exception:--
These exceptions are the object of the Exception class or any of its subclasses except Runtime exception class. These condition arises due to invalid input,problem with your network connectivity & problem in database. IOException,SQLException,DataAccessException,ClassNotFoundException & MalformedURLException are the Checked Exception. This Exception is thrown when there is an error in I/O operation. In this case operation is normally terminated.
2) Unchecked Exception:--
These exceptions arises during run-time that occur due to invalid argument passed to method. The java compiler doesn't check the program error during compilation. e.g ArithmeticException, NumberFormatException, NullPointerException, IndexOutOfBoundsException, ClassCastException & IllegalArgumentException etc.
Does method can return exception ?
Method does not return exception but it will throw an exception.
What happens when exception is thrown by main method?
When exception is thrown by main , Java runtime system terminates.
What is OutOfMemoryError in Java?
OutOfMemoryError is when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. OutOfMemoryError in Java is a subclass of VirtualMachineError.
What is difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when an application tries to load in a class through its string name using:
The forName method in class Class.
The findSystemClass method in class ClassLoader .
The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.
NoClassDefFoundError is thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found. For more details, Refer Difference between NoClassDefFoundError and ClassNotFoundException in Java
Related Post :--
1) How to create the custom exception in Java?
2) String Interview Questions and Answers
3) Difference between final,finalize and finally in Java
4) Exception Handling in method overriding in Java
5) Static Keyword and Its usage in Java
6) Factory Design Pattern in Java
7) Difference between NoClassDefFoundError and ClassNotFoundException in Java

i had found necessary info here...gud 1
ReplyDeleteThanks for comment...Keep visiting and happy coding.
ReplyDeleteGreat one :)
ReplyDeletenice article...
ReplyDeleteException handling best practices refer this from Lokesh Gupta Top 20 Java Exception Handling Best Practices
ReplyDeleteAmazing Post Thanks for sharing
ReplyDeleteyou provided a great information hacking course online
ReplyDelete