by Debasis Samanta
This Chapter discusses exceptions handling mechanism in Java. An exception is an abnormal condition that can occur during the execution time of a program. If these exceptions are not prevented or at least handled properly, either the program will be aborted abnormally, or the incorrect result will be carried on. In traditional programming languages like C, Pascal etc. this exception handling is an overhead of the programmer to make the program robust by including lot of if statement and error-handler routine which make the programs more complicated. Java programmer are released from this overhead by the exception handling mechanism in Java.
To handle the common possible exceptions ,Java defined a class hierarchy as shown below :
Here, the class Throwable is used to represent all exceptional conditions. Two immediate subclasses of Throwable are Exception, and Error. The class Exception is used for exceptional conditions that user programs can catch. The other branch of the throwable tree is the class Error, which defines the conditions that should not be expected to be caught under normal circumstances. These class is responsible for giving errors in some catastrophic failures. A further refinement is there by a sub class of Exception, which is for exceptional condition that created by the run time called RuntimeException. These exceptions are typically created automatically during the run time in response to some execution error. A list of exceptions that a programmer can catch in the program is summarized below :
RuntimeException sub classes : Error sub classes : ArithmeticException ClassCirculatoryError ArrayIndexOutofBoundException ClassFormatError ArrayStoreException Error ClassCasteException IllegalAccessError IlegalArgumentException IncompatibleClassChangeError IndexOutofBoundException InstantiationError NegativeArraySizeException LinkageError NullPointerException NoCassDefFoundError NumberFormatException NoSuchFieldError SecurityException NoSuchMethodError StringIndexOutofBoundException OutofMemoryError StackOverflowError Exception sub classes: Throwable ClassNotFoundException UnknownError DataFormatException UnsatisfiedLinkError IllegalAccessException VerifyError InstantiationException VirtualMachineError InterruptedException NoSuchMethodException RuntimeException
Java's exception handling brings Run Time Error Management into the object oriented world. During the execution of a program, when an exceptional condition arises, an object of the respective exception class is created and thrown in the method which caused the exception. That method may choose to catch the exception and then can guard against premature exit or may have a block of code execute.
Java exception handling is managed via five key words : try, catch, throw, throws, and finally. Here is the basic form of an exception handling block.
try { // block of code } catch ( ExceptionType1 e) { // Exception handling routine for ExceptionType1 (optional) } catch (ExceptionType2 e ) { // Exception handling routine for ExceptionType2 (optional) } . . . catch (ExceptionType_n e) { // Exception handling routine for ExceptionType_n (optional) } finally { // Program code of exit (optional) }
This structure implements that, when you try to execute a block of code, and if an error occurs, you may catch based on what type of exception it is, or finally dealt with by a default handler.
It is better to illustrate the mechanism with few simple examples.
Illustration 5.1 // simple example of Exception handling // Consider the following code in Java : class DivideZero { static int anyFunction ( int x, int y ) { int a = x/y; return (a); } public static void main (String args [ ] ) { int result = anyFunction (25, 0) ; // Exception occurs here as y = 0 System.out.println ( " Result : " + result ); } }
This is a code where an exception will occur in this example (when the value of the second argument is passed as 0), we have not coded an exception handler; but Java provides a default run time handler. In this case, when the Java run time tries to execute the division, it notices that the denominator is zero and then instantiate an Exception object (namely ArithmeticException ) to cause this code to stop and deal with this error condition. The default handler prints out the exception message. One can easily see it if this program is run. Following output is expected :
C:\> java DivideZero // To run the Application DivideZero
One can notice the output then : Java . lang . Arithmetic Exception : / by zero at DivideZero.Any Function (DivideZero.Java : 3) at DivideZero.main (DivideZero.Java : 7)
Note : Note that how default run time handler can print where is the source and what kind of exception it is.
Illustration 5.2 /* Showing compile time errors in a program. */ Class Error { Public static void main (string args [ ]) { system.out.print("Can you find errors in me?") } } class AnotherError { public void insert( ){ System.out.print("To insert a text"); } abstract void delete( ){ System.out.print("To delete a text"); } } /*Note: A class file can be compiled successfully, if it is syntactically correct, even there is no main class, that is, with main method. */
It is observed that Java's default run time handler displays the detail of an exception and execution suspended as soon as an error encountered, but it is often more desirable to handle the exception yourself and continue running. The try key word can be used to specify a block of code that should be guarded against all exceptions. Immediately following a try block, you should include a catch clause which specifies the exception type that you wish to catch.
Illustration 5.3 /* Showing run-time errors in a program. */ class Demonstration_102 { public static void main (String args [ ]) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = a/b; System.out.println("Value of c =" + c); } } /*Note: Run this program with the following input: java Error 1 2 java Error 10 20 30 java Error 40 java Error 4.5 5 */
Illustration 5.4 /* Run the following program without exception-handling mechanism for some input */ public class Demonstration_103 { static int anyFunction (int x, int y ){ int a = x/y; return a; } public static void main (String args[]) { int a,b, result; a=0; b=0; System.out.print("Enter any two integers : "); a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]); result = anyFunction (a, b); System.out.println ( "Result : " + result); } } /*Note: Run this program with the following input: java Demonstration_103 200 10 java Demonstration_103 10 0 */
Illustration 5.5 /* Run the following program with exception handling mechanism for some input */ // Case : Simple try-catch block…… public class Demonstration_104 { static int anyFunction (int x, int y ){ try { int a = x/y; return a; } catch (ArithmeticException e) { System.out.println ( "Division by zero" ); } return 0; } public static void main (String args[]) { int a,b, result; a=0; b=0; try{ a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]); System.out.print("Value of a and b = "+a+" "+b); }catch(Exception e){} result = anyFunction (a, b); System.out.println ( "\nResult : " + result); } } /*Note: Run this program with the following input: java Demonstration_104 200 10 java Demonstration_104 10 0 */
Illustration 5.6 /* The following program with exception handling mechanism shows how robust it while it is in execution */ class Demonstration_105 { public static void main (String args[ ]){ int number, InvalidCount = 0, validCount = 0; for (int i = 0; i < args.length; i++) { try { number = Integer.parseInt(args[i]); } catch (NumberFormatException e){ InvalidCount++; System.out.println ("Invalid number at " + i +" "+ args[i]); } validCount++; System.out.println ("Valid number at " + i+" "+ args[i]); } System.out.println ("Invalid entries: " + InvalidCount); System.out.println ("Valid entries: " + validCount); } } /*Note: Run this program with the following input: java Demonstration_105 1 2 3 java Demonstration_105 10 20 30 40 java Demonstration_105 1.0 2 3.0 40 java java Demonstration_105 4.5 5 */
Illustration 5.7 /* Run the following program without exception handling mechanism for some input */ // Case : try with multiple catch block…… public class Demonstration_106 { public static void main (String args[ ]) { int i = args.length; // No of arguments in the command line String myString[] = new String[i]; myString[0]=args[0]; if(myString[0].equals("Java")) { System.out.println("First word is Java !"); } System.out.println( " Number of arguments = " + i ); int x = 12/ i; int y[ ] = {555, 999}; y[ i ] = x; } } /*Note: Run this program with the following input: java Demonstration_106 java Demonstration_106 Java java Demonstration_106 I love Java java Demonstration_106 10 20 30 40 */
Next let us see, the multiple use of catch clauses, let us take a look at the Illustration 5.8.
Illustration 5.8 /* Run the following program with exception handling mechanism for the same input */ // Case : try with multiple catch block…… public class Demonstration_107 { public static void main (String args[ ]) { try { int i = args.length; // No of arguments in the command line String myString[] = new String[i]; // If i = 0 then myString null pointer error if(myString[0].equals("Java")){ // #1 // System.out.println("First word is Java !"); } System.out.println( " Number of arguments = " + i ); int x = 12/ i; // # 2 // int y[ ] = {555, 999}; // y is an array of size 2 with index 0,1 y[ i ] = x; //#3// Index is out-of-range may occur if i > 1 } catch (ArithmeticException e ) { // To catch the error at #2 System.out.println ( " Div by 0 : "+ e ); } catch (NullPointerException e ) { // To catch the error at #1 System.out.println ( "A null pointer exception :" + e ); } catch (ArrayIndexOutOfBoundsException e ) { // To catch the error at #3 System.out.println ("Array Index OOB : " + e); } } } /*Note: Run this program with the following input: java Demonstration_106 java Demonstration_106 Java java Demonstration_106 I love Java java Demonstration_106 10 20 30 40 */
For different kind of errors, corresponding catch clause will catch the respective exception.Instead of using multiple catches, only one catch clause can handle number of exceptions at a time. Following is an illustration for this :
Illustration 5.9 /* Multiple errors with single catch block… */ class Demonstration_108 { public static int j; public static void main (String args[ ] ) { for (int i = 0; i < 4; i++ ) { try { switch (i) { case 0 : int zero = 0; j = 999/ zero; // Divide by zero break; case 1: int b[ ] = null; j = b[0] ; // Null pointer error break; case 2: int c[] = new int [2] ; j = c[10]; // Array index is out-of-bound break; case 3: char ch = "Java".charAt(9) ;// String index is out-of-bound break; } } catch (Exception e) { System.out.println("In Test case#"+i+ "\n"); System.out.println (e.getMessage() ); } } } }
OUTPUT: |
In Test case#0 |
Exception handling is in fact built with try-catch-finally construct, although the finally clause is purely optional. But in some cases, it is required to execute few codes regardless of whether an exception was caught or not. For example, before exiting a program, it may have to close some open files and freeing up any other resources that might have been allocated at the beginning of a method. The finally clause defines a block of code which will be executed always irrespective of any exception occurs or not. Consider the use of the Illustration 5.10 to give a demonstration of the use of finally :
Illustration 5.10 /* finally in try-catch block */ class Demonstration_109 { public static void main (String [ ] args ) { int i = 0; String greetings[] = {"Hello Twinkle !", "Hello Java !", "Hello World ! "}; while ( i < 4) { try { System.out.println (greetings [i] ); i++; }catch (Exception e ) { System.out.println (e.toString() ); // Message of exception e in String format } finally { System.out.println (" Hi !"); if (i < 3); else {System.out.println("You should quit and reset index value");break;} } } // while ( ) } // main ( ) } // class
OUTPUT: |
Hello Twinkle ! |
If you run this program, you will see that the code in finally block will be executed always the loop is iterated.
In Java, throw key word is known by which user can throw an exception of their own instead of automatic exception object generated by Java run time. To use this, we have to create an instance of Throwable object. Then the throw key word can be used to throw this exception. Following is the Illustration 5.11 to clear this idea :
Illustration 5.11 /* Use of throws clause in exception handling */ import java.lang.*; public class Demonstration_1010 { public static void main(String Args[]) throws Exception{ int[] array = new int[3]; try{ for (int i=0;i<4;++i) { array[i] = i; } System.out.println(array); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("filIn: " + e.fillInStackTrace()); System.out.println("cause: " + e.getCause()); System.out.println("local: " + e.getLocalizedMessage()); System.out.println("messa: " + e.getMessage()); System.out.println("trace: " + e.getStackTrace()); System.out.println(); System.out.println(); System.out.print("trace: "); e.printStackTrace(); System.out.println(); System.out.print("string: "); e.toString(); System.out.println(); System.out.println(); //printed just to inform that we have entered the catch block System.out.println("Oops, we went too far, better go back to 0!"); throw (Exception) new Exception().initCause(e); } finally{ System.out.println(array); // method call to continue program } } }
Illustration 5.12a /* Necessity of nested try-catch example …*/ class Demonstration_1011a { public static void main(String args[]) { int a = args.length; int b = 42 / a; // Divide-by-zero exception System.out.println("a = " + a); if(a==1) a = a/(a-1);// // Another divide-by-zero exception if(a==2) { int c[ ] = { 1 }; c[2] = 99; // out-of-bound exception, if two argments } } } /*Note: Run the program with the following output java Demonstration_1011a 1 2 3 java Demonstration_1011a 1 2 java Demonstration_1011a 1 java Demonstration_1011a 1 */
Illustration 5.12b /* Remedy with nested try-catch example …*/ class Demonstration_1011b { public static void main(String args[]) { try { // To catch divide-by-zero int a = args.length; int b = 42 / a; // divide-by-zero exception System.out.println("a = " + a); if(a==1) a = a/(a-a); // another divide-by-zero exception try { // nested try block if(a==2) { // If two command-line args are used, then an out-of-bounds exception int c[ ] = { 1 }; c[2] = 99; } }catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } }catch(ArithmeticException e) { System.out.println("Divide by 0:"+e); } } } /*Note: Run the program with the following output java Demonstration_1011a 1 2 3 java Demonstration_1011a 1 2 java Demonstration_1011a 1 java Demonstration_1011a 1 */
In previous Section of this Chapter, we have listed the different classes for handling exceptions in Java. In this Section, let us get a brief introduction about the main of them :
ArithmeticException: An ArithmeticException is thrown if one try to divide an integer by zero or take a modules by zero. For example, the following code causes an ArithmeticException to be thrown:
int wrongMath ( ) { int n = 100; int result ; for (int i = 9; i > -1; i- - ) result = n % i; // modulo remainder. return (result ); }
ArrayIndexOutofBoundsException : In ArrayIndexOutofBoundsException is thrown when one try to access an array element that is out of bounds, meaning that one using an index of less than zero or greater than or equal to the size of the array. Here is a token example that would throw an ArrayIndexOutofBoundsException :
void wrongArrayAccess ( ) { int anArray = new int[10] ; // An array of size having index 0,1,..,9 …….. anArray[10] = 999 ; // index out of range }
ArrayStoreException : This exception occurs when one try to store a value into an array of incompatible class or type. Following is an example where ArrayStoreException will be thrown.
void badArrayStore ( ) { int storeArray = new int[15]; // An array of integers boolean boolArray =new boolean[5]; // An array of booleans System.arraycopy(storeArray, 2, boolArrary, 2, 4); // Copy the element boolArray[3,4,5] into storeArray starting at storeArray[2] }
ClassCastException : In Java, an instance of a class of one type can be possible to cast for another type. Here an instance of class can be casted to its super class but one can not cast an instance of class to its subclasses. If one attempt this cast, a ClassCasteException will occur. The following example, results a ClassCastException at run time :
class ClassA { // a token of a simple class ……… } class ClassB extends ClassA{ // A sub class of ClassA ………. void bMethod ( ) { . . . . } } class Test { void wrongCast ( ) { ClassA anInstanceA = new ClassA( ); ClassB anInstanceB = (Class B ) anInstanceA; // Exception anInstanceB.bMethod ( ); } }
IllegalArgumentException : This IllegalArgumentException occurs when one attempt to pass a parameter that is not in valid range or value for the method. The following method throws an IllegalArgumentException if passed an illegal parameter value:
Not that, in the above example, method wrongArgumentPass(int) throws an exception when caller passes unacceptable value.static void wrongArgumentPass (int agru ) { if (argu == 0) throw new IllegalArgumentException ( "Argument cannot be 0 "); int x = 555 / argu; }
IllegalThreadStateException : This exception is thrown by some methods in the system package classes when one try to illegally change the state of thread, for example, by trying to start a thread that is already running.
IndexOutofBoundsException : This exception can be thrown in a method when one passed an index value that is out side an acceptable range. Example is already visited in ealier discussions.
NegativeArraySizeException : This exception is thrown when an array with a negative size is attempted to be allocated. The following method results in a NegativeArraySizeException at run time :
Void negativeSizeArray ( ) { int theSize = -5; int foolArray = new int[theSize]; }
NullPointerException : This exception is thrown when one attempt to use a method or variable in a variable name that contains a null object reference. The following method results in a NullPointerException at run time:
void nullPointer ( ) { String myString = null; // myString is a null reference object if ( myString.equals (" Sahara" )) { System.out.println (" Howz!"); } }
NumberFormatException : This exception is thrown by some methods in classes of System package when one try to convert an invalid string to a number or vice versa.
SecurityException : This exception is thrown by some methods in the System package when one attempt to call a method that will perform an action not allowed by the current security settings of the browser within which the applet code is running. It can also be thrown if the program denies permission when prompted whether to allow an action such as writing to a file.
StringIndexOutOfBoundsException : A StringIndexOutOfBoundsException is thrown when one try to access a character that is out of the bounds of a string, meaning that using an index of less than zero or greater than or equal to the length of the string. Following is an example that would throw a StringIndexOutOfBoundException :
void wrongStringIndex ( ) { String theString = " N E R I S T", char theChar = theString.charat(20); // Index should be between 0 and 10 }
ClassNoFoundException : This exception is thrown by the class loader when a class file is not found when a class is attempted to be instantiated.
DataFormatException : This exception is thrown when data being read from a string appears to be in an invalid format.
IllegalAccessException : This exception is thrown by methods in java.lang class when instantiating a class by its name if the class is not public or there is no public constructor. One might encounter this exception if calling a method that, in turn, calls one of these methods.
InstantiationException : This exception is thrown when an attempt is made to instantiate an abstract class, primarily by methods in java.lang class when instantiating a class by its name.
InterruptedException : This exception is thrown within a thread when it is interrupted by some other thread. This exception will be illustrated during the discussion of Thread in Java.
NoSuchMethodException : This exception is thrown when a particular method in an object or class cannot be found.
The information about other less frequently used exceptions can be obtained in details from Chapter 2 of Part III in this book.
Practice 5.1 public class DivideZero { static int anyFunction (int x, int y ){ try { int a = x/y; return a; } catch (ArithmeticException e) { System.out.println ( "Division by zero" ); } return 0; } public static void main (String args[]) { int a,b, result; a=0; b=0; System.out.print("Enter any two integers : "); try{ a = System.in.read(); b = System.in.read(); }catch(Exception e){} result = anyFunction (a, b); System.out.println ( "Result : " + result); } } Find out the types of exceptions.
Practice 5.2 class CommandLineInput { public static void main (String args[ ] { int number, InvalidCount = 0; validCount = 0; for (int i = 0; i < args.length; i++) { try { number = Integer.parseInt(args[i]); } catch (NumberFormatException e) { inavlidCount++; System.out.println ( “Invalid number at “ + i + args.[i]); } validCount++; System.out.println ( “Valid number at “ + i + args.[i]); } System.out.println ( “Invalid entries: “ + inValidCount); System.out.println ( “Valid entries: “ + validCount); } } } Find out the types of exceptions.
Practice 5.3 public class MultiCatch { public static void main (String args[ ]) { try { int i = args.length; // No of arguments in the command line String myString[] = new String[i]; // If i = 0 then myString null pointer error // #1 // if(myString[0].equals(“Java”)); System.out.println("First word is Java !"); System.out.println( " Number of arguments = " + i ); // # 2 // int x = 18/ i; int y[ ] = {555, 999}; // y is an array of size 2 and index are 0,1 // #3 // y[ i ] = x; // Index is out-of-range may occur if i > 1 } catch (ArithmeticException e ) { // To catch the error at #2 System.out.println ( " Div by 0 : "+ e ); } catch (NullPointerException e ) { // To catch the error at #1 System.out.println ( "A null pointer exception :" + e ); } catch (ArrayIndexOutOfBoundsException e ) { // To catch the error at #3 System.out.println ("Array Index OoB : " + e); } } } Find out the types of exceptions.
Practice 5.4 import java.lang.*; public class exceptions{ public static void main(String Args[]) throws Exception{ int[] array = new int[3]; try{ for (int i=0;i<4;++i) { array[i] = i; } System.out.println(array); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("filIn: " + e.fillInStackTrace()); System.out.println("cause: " + e.getCause()); System.out.println("local: " + e.getLocalizedMessage()); System.out.println("messa: " + e.getMessage()); System.out.println("trace: " + e.getStackTrace()); System.out.println(); System.out.println(); System.out.print("trace: "); e.printStackTrace(); System.out.println(); System.out.print("string: ");e.toString(); System.out.println(); System.out.println(); //printed just to inform that we have entered the catch block System.out.println("Oops, we went too far, better go back to 0!"); throw (Exception) new Exception().initCause(e); } finally{ System.out.println(array); //method call to continue program } } } Find out the types of exceptions.
Practice 5.5 class ExceptionTest { public static int j; public static void main (String args[ ] ) { for (int i = 0; i < 4; i++ ) { try { switch (i) { case 0 : int zero = 0; j = 999/ zero; // divide by zero break; case 1: int b[ ] = null; j = b[ 0] ; // Null pointer error break; case 2 : int c[] = new int [2] ; j = c[10]; // Array index is out-of-bound break; case 3 : char ch = "Java".charAt(9) ; // String index is out-of-bound break; } // switch } // try catch (Exception e) { // To catch an exception System.out.println "In Test case # " + i + "\n" ); System.out.println (e) ; } // catch } // main } // class } Find out the types of exceptions.
Practice 5.6 // Use of finally in try-catch // class FinallyDemo { public static void main (String [ ] args ) { int i = 0; String greetings [ ] = { "Hello Twinkle !", "Hello Java !", "Hello World ! " }; while ( i < 4) { try { System.out.println (greetings [i] ); }catch (Exception e ) { System.out.println (e.toString()); // message of exception e in String format System.out.println("Resetting index value"); } finally { System.out.println (" Hi !"); i ++; } } // while ( ) } // main ( ) } // class Find out the types of exceptions.
Practice 5.7 // File Name BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $"+ e.getAmount()); e.printStackTrace(); } } } // File Name CheckingAccount.java //create a separate class file and name it as CheckingAccount.java. Then paste the following class //contents there. public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; } } // File Name InsufficientFundsException.java //create a separate class file and name it as InsufficientFundsException.java. Then paste the following class contents there. public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } Find out the types of exceptions.
Practice 5.8 import java.io.*; public class exceptionHandle{ public static void main(String[] args) throws Exception{ try{ int a,b; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); a = Integer.parseInt(in.readLine()); b = Integer.parseInt(in.readLine()); } catch(NumberFormatException ex){ System.out.println(ex.getMessage() + " is not a numeric value."); System.exit(0); } } } Find out the types of exceptions.
Is there any way to "get around" the strict restrictions placed on methods by the throws clause? | |
Differences between exceptions, errors, and runtime exceptions. |
What is an exception? | |
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. | |
What is 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. | |
Which is superclass of Exception? | |
"Throwable", the parent class of all exception related classes. | |
What are the advantages of using exception handling? | |
Exception handling provides the following advantages over "traditional" error management techniques:
| |
Why Runtime Exceptions are Not Checked? | |
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in runtime exceptions. The information available to a compiler, and the level of analysis the compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers. | |
What is the use of finally block? | |
The finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. This is right place to close files, release your network sockets, connections, and perform any other cleanup your code requires.
Note: If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. It there was an exception thrown, the finally block executes immediately after the proper catch block completes | |
Can we have the try block without catch block? | |
Yes, we can have the try block without catch block, but finally block should follow the try block.
Note: It is not valid to use a try clause without either a catch clause or a finally clause. | |
What is the difference throw and throws? | |
throws: Used in a method's signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as throwing a particular class of exceptions, then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself.
A method that does not handle an exception it throws has to announce this: public void myfunc(int arg) throws MyException { … }throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. To throw an user-defined exception within a block, we use the throw command: throw new MyException("I always wanted to throw an exception!"); | |
How to create custom exceptions? | |
By extending the Exception class or one of its subclasses.
Example: class MyException extends Exception { public MyException() { super(); } public MyException(String s) { super(s); } } | |
What are the different ways to handle exceptions? | |
There are two ways to handle exceptions:
| |
What are the types of Exceptions in Java? | |
There are two types of exceptions in Java, unchecked exceptions and checked exceptions.
| |
Why Errors are Not Checked? | |
A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be pointlessly. |