In Java 8 language which of the following statements is incorrect about assertion
Exception HandlingIntroductionAn exception is an abnormal event that arises during the execution of the program and disrupts the normal flow of the program. Abnormality do occur when your program is running. For example, you might expect the user to enter an integer, but receive a text string; or an unexpected I/O error pops up at runtime. What really matters is "what happens after an abnormality occurred?" In other words, "how the abnormal situations are handled by your program." If these exceptions are not handled properly, the program terminates abruptly and may cause severe consequences. For example, the network connections, database connections and files may remain opened; database and file records may be left in an inconsistent state. Show Java has a built-in mechanism for handling runtime errors, referred to as exception handling. This is to ensure that you can write robust programs for mission-critical applications. Older programming languages such as C have some drawbacks in exception handing. For example, suppose the programmer wishes to open a file for processing:
Java overcomes these drawbacks by building the exception handling into the language rather than leaving it to the discretion of the programmers:
Let's look into these three points in more details. Point 1: Exceptions must be DeclaredAs an example, suppose that you want to use a public Scanner(File source) throws FileNotFoundException; The method's signature informs the programmers that an exceptional condition "file not found" may arise. By declaring the exceptions in the method's signature, programmers are made to aware of the exceptional conditions in using the method. Point 2: Exceptions must be HandledIf a method declares an exception in its signature, you cannot use this method without handling the exception - you can't compile the program. Example 1: The program did not handle the exception declared, resutled in compilation error. import java.util.Scanner;
import java.io.File;
public class ScannerFromFile {
public static void main(String[] args) {
Scanner in = new Scanner(new File("test.in"));
}
} ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Scanner in = new Scanner(new File("test.in"));
^ To use a method that declares an exception in its signature, you MUST either:
Example 2: Catch the exception via a " import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class ScannerFromFileWithCatch { public static void main(String[] args) { try { Scanner in = new Scanner(new File("test.in")); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } } If the file cannot be found, the exception is caught in the catch-block. In this example, the error handler simply prints the stack trace, which provides useful information for debugging. In some situations, you may need to perform some clean-up operations, or open another file instead. Take note that the main logic in the try-block is separated from the error handling codes in the catch-block. Example 3: You decided not to handle the exception in the current method, but throw the exception up the call stack for the next higher-level method to handle. import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class ScannerFromFileWithThrow { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File("test.in")); } } In this example, you decided not to handle the Point 3: Main logic is separated from the exception handling codesAs shown in Example 2, the main logic is contained in the try-block, while the exception handling codes are kept in the catch-block(s) separated from the main logic. This greatly improves the readability of the program. For example, a Java program for file processing could be as follows: try { open file; process file; ...... } catch (FileNotFoundException ex) { } catch (IOException ex) { } finally { close file; } Method Call StackA typical application involves many levels of method calls, which is managed by a so-called
method call stack. A stack is a last-in-first-out queue. In the following example,
Enter main() Enter methodA() Enter methodB() Enter methodC() Exit methodC() Exit methodB() Exit methodA() Exit main() As seen from the output, the sequence of events is:
suppose that we modify public static void methodC() { System.out.println("Enter methodC()"); System.out.println(1 / 0); System.out.println("Exit methodC()"); } The exception message clearly shows the method call stack trace with the relevant statement line numbers: Enter main() Enter methodA() Enter methodB() Enter methodC() Exception in thread "main" java.lang.ArithmeticException: / by zero at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22) at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16) at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10) at MethodCallStackDemo.main(MethodCallStackDemo.java:4)
Exception & Call StackWhen an exception occurs
inside a Java method, the method creates an This process is illustrated as follows. Suppose that Exception Classes - Throwable, Error, Exception & RuntimeExceptionThe figure below shows the hierarchy of the
Checked vs. Unchecked ExceptionsAs illustrated, the subclasses of All the other exception are called checked exceptions. They are checked by the compiler and must be caught or declared to be thrown. Exception Handling OperationsFive keywords are used in exception handling: Java’s exception handling consists of three operations:
Declaring ExceptionsA Java method must declare in its signature the types of checked exception it may "throw" from its body, via the keyword "throws". For example, suppose that public void methodD() throws XxxException, YyyException {
} The
method's signature indicates that running Exceptions belonging to Throwing an ExceptionWhen a Java operation encounters an abnormal
situation, the method containing the erroneous statement shall create an appropriate public void methodD() throws XxxException, YyyException { ... ... if ( ... ) throw new XxxException(...); ... if ( ... ) throw new YyyException(...); ... } Note that the keyword to declare exception in the method's signature is " Catching an ExceptionWhen a method throws an exception, the JVM searches backward through the call stack for a matching exception handler. Each exception handler can handle one particular class of exception. An exception handler handles a specific class can also handle its subclasses. If no exception handler is found in the call stack, the program terminates. For example, suppose public void methodD() throws XxxException, YyyException { ...... } To use
try-catch-finallyThe syntax of try-catch-finally is: try { ...... } catch (Exception1 ex) { ...... } catch (Exception2 ex) { ...... } finally { ...... } If no exception occurs during the running of the try-block, all the catch-blocks are skipped, and finally-block will be executed after the try-block. If one of the statements in the try-block throws an exception, the Java runtime ignores the rest of the statements in the try-block, and begins searching for a matching exception handler. It matches the exception type with each of the catch-blocks sequentially. If a catch-block catches that exception class or catches a superclass of that exception, the statement in that catch-block will be executed. The statements in the finally-block are then executed after that catch-block. The program continues into the next statement after the try-catch-finally, unless it is pre-maturely terminated or branch-out. If none of the The Example 1
This is the output when the Start of the main logic Try opening a file ... File Not Found caught ... finally-block runs regardless of the state of exception After try-catch-finally, life goes on... This is the output when no exception triggered: Start of the main logic Try opening a file ... File Found, processing the file ... End of the main logic finally-block runs regardless of the state of exception After try-catch-finally, life goes on... Example 2
Enter main() Enter methodA() finally in methodA() Exception in thread "main" java.lang.ArithmeticException: / by zero at MethodCallStackDemo.methodA(MethodCallStackDemo.java:11) at MethodCallStackDemo.main(MethodCallStackDemo.java:4) try-catch-finally
What if I really don't care about the exceptionsCertainly not advisable
other than writing toy programs. But to bypass the compilation error messages triggered by methods declaring unchecked exceptions, you could declare " public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File("test.in")); ...... } Overriding and Overloading MethodsAn overriding method must have the same argument list and return-type (or subclass of its original from JDK 1.5). An overloading method must have different argument list, but it can have any return-type. An overriding method
cannot have more restricted access. For example, a method with An overriding method cannot declare exception types that were not declared in its original. However, it may declare exception types are the same as, or subclass of its original. It needs not declare all the exceptions as its original. It can throw fewer exceptions than the original, but not more. An overloading method must be differentiated by its argument list. It cannot be differentiated by the return-type, the exceptions, and the modifier, which is illegal. It can have any return-type, access modifier, and exceptions, as long as it can be differentiated by the argument list. Common Exception ClassesArrayIndexOutOfBoundsException: thrown by JVM when your code uses an array index, which is is outside the array's bounds. For example, int[] anArray = new int[3]; System.out.println(anArray[3]); Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 NullPointerException: thrown by the JVM when your code attempts to use a null reference where an object reference is required. For example, String[] strs = new String[3]; System.out.println(strs[0].length()); Exception in thread "main" java.lang.NullPointerException NumberFormatException: Thrown programmatically (e.g., by Integer.parseInt("abc"); Exception in thread "main" java.lang.NumberFormatException: For input string: "abc" ClassCastException: thrown by JVM when an attempt is made to cast an object reference fails. For example, Object o = new Object(); Integer i = (Integer)o; Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Integer IllegalArgumentException: thrown programmatically to indicate that a method has been passed an illegal or inappropriate argument. You could re-use this exception for your own methods. IllegalStateException: thrown programmatically when a method is invoked and the program is not in an appropriate state for that method to perform its task. This typically happens when a method is invoked out of sequence, or perhaps a method is only allowed to be invoked once and an attempt is made to invoke it again. NoClassDefFoundError: thrown by the JVM or class loader when the definition of a class cannot be found. Prior to JDK 1.7, you will see this exception call stack trace if you try to run a non-existent class. JDK 1.7 simplifies the error message to "Error: Could not find or load main class xxx". Creating Your Own Exception ClassesYou should try to reuse the Note that Example
The output is as follows: hello MyMagicException: you hit the magic number at MyMagicExceptionTest.magic(MyMagicExceptionTest.java:6) at MyMagicExceptionTest.main(MyMagicExceptionTest.java:14) Assertion (JDK 1.4)JDK 1.4 introduced a new keyword called The assert booleanExpr; assert booleanExpr : errorMessageExpr; When the runtime execute the assertion, it first evaluates the Assertion is useful in detecting bugs. It also serves to document the inner workings of you program (e.g., pre-conditions and post-conditions) and enhances the maintainability. One good candidate for assertion is the switch-case statement where the programmer believes that one of the cases will be selected, and the default-case is not plausible. For example,
Assertion, by default, are disabled to ensure that they are not a performance liability in the production environment. To enable assertion, use the runtime command-line option In the above example, " > javac AssertionSwitchTest.java > java -ea AssertionSwitchTest Exception in thread "main" java.lang.AssertionError: % at AssertionSwitchTest.main(AssertionSwitchTest.java:11) > java AssertionSwitchTest 5 % 6 = 0 In the above example, since the " default: throw new AssertionError("Unknown operator: " + operator); Another usage of assertion is to assert "internal invariants". In other words, to assert the possible values of an internal variable. For example,
> java -ea AssertionSwitchTest Exception in thread "main" java.lang.AssertionError: -5 at AssertionTest.main(AssertionTest.java:5) Assertion can be used for verifying:
Pre-conditions of public methodsAssertion should not be used to check the validity of
the arguments (pre-condition) passed into "public" method. It is because public Time(int hour, int minute, int second) { if(hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) { throw new IllegalArgumentException(); } this.hour = hour; this.minute = minute; this.second = second; } Example[TODO] Example on pre-condition (private method), post-condition, and class invariant. LINK TO JAVA REFERENCES & RESOURCES Which statement is true about assertions in the Java programming language?Explanation: Option A is correct. Because assertions may be disabled, programs must not assume that the boolean expressions contained in assertions will be evaluated. Thus these expressions should be free of side effects.
Which three statements are true about assertion?Which three statements are true? Assertion checking is typically enabled when a program is deployed. It is never appropriate to write code to handle failure of an assert statement. Assertion checking is typically enabled during program development and testing.
Which of the following exception is generated by assertion statements?Answer: The AssertionError thrown by the assert statement is an unchecked exception that extends the Error class. Thus assertions are not required to declare them explicitly and also there is no need to try or catch them.
What can cause an assertion statement to be ignored in Java?Yes, When Java program is compiled, with assertions enabled/disabled, it is marked in the generated class file. So when class-loader loads your file and run the instruction or line is completely ignored if assertions were disabled.
|