Java Throw Exception Example and Then Ask Again

Java Programming

Exception Handling & Assertion

Exception Handling

Introduction

An exception is an abnormal event that arises during the execution of the program and disrupts the normal flow of the program. Abnormality exercise occur when your program is running. For example, yous might await the user to enter an integer, but receive a text string; or an unexpected I/O error pops upwardly at runtime. What really matters is "what happens after an abnormality occurred?" In other words, "how the aberrant situations are handled by your programme." If these exceptions are not handled properly, the plan terminates abruptly and may cause astringent consequences. For instance, the network connections, database connections and files may remain opened; database and file records may exist left in an inconsistent land.

Java has a born mechanism for handling runtime errors, referred to as exception handling. This is to ensure that you tin can write robust programs for mission-critical applications.

Older programming languages such as C take some drawbacks in exception handing. For example, suppose the programmer wishes to open a file for processing:

  1. The programmers are not made to aware of the exceptional conditions. For example, the file to exist opened may not necessarily be. The developer therefore did non write codes to test whether the file exists before opening the file.
  2. Suppose the programmer is aware of the exceptional conditions, he/she might decide to finish the main logic first, and write the exception treatment codes later – this "later", unfortunately, usually never happens. In other words, you lot are not force to write the exception treatment codes together with the main logic.
  3. Suppose the programmer decided to write the exception handling codes, the exception handling codes intertwine with the main logic in many if-else statements. This makes main logic hard to follow and the unabridged program hard to read. For case,
    if (file exists) {    open up file;    while (there is more records to exist candy) {       if (no IO errors) {          procedure the file tape       } else {          handle the errors       }    }    if (file is opened) shut the file; } else {    study the file does not exist; }

Java overcomes these drawbacks past building the exception handling into the language rather than leaving it to the discretion of the programmers:

  1. You lot will be informed of the exceptional conditions that may arise in calling a method - Exceptions are declared in the method's signature.
  2. You are forced to handle exceptions while writing the main logic and cannot leave them every bit an reconsideration - Your program cannot compiled without the exception handling codes.
  3. Exception handling codes are separated from the primary logic - Via the endeavor-take hold of-finally construct.

Let's wait into these three points in more details.

Point 1: Exceptions must be Declared

As an example, suppose that you want to use a java.util.Scanner to perform formatted input from a disk file. The signature of the Scanner'southward constructor with a File argument is given as follows:

public Scanner(File source)          throws FileNotFoundException;

The method's signature informs the programmers that an infrequent condition "file not found" may arise. By declaring the exceptions in the method's signature, programmers are made to aware of the exceptional weather condition in using the method.

Betoken 2: Exceptions must be Handled

If a method declares an exception in its signature, yous cannot use this method without handling the exception - you can't compile the programme.

Example one: 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.coffee: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:

  1. provide exception handling codes in a "try-grab" or "try-catch-finally" construct, or
  2. not treatment the exception in the current method, but declare the exception to be thrown up the call stack for the next higher-level method to handle.

Example 2: Catch the exception via a "endeavour-catch" (or "endeavor-catch-finally") construct.

import java.util.Scanner; import java.io.File;          import java.io.FileNotFoundException;          public form ScannerFromFileWithCatch {    public static void main(String[] args) {          try {          Scanner in =          new Scanner(new File("exam.in"));                    } catch (FileNotFoundException ex) {                    ex.printStackTrace();                    }          } }

If the file cannot be found, the exception is caught in the catch-cake. In this instance, the error handler simply prints the stack trace, which provides useful information for debugging. In some situations, you may need to perform some clean-upward operations, or open some other file instead. Accept note that the master 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 electric current method, merely throw the exception upwards the telephone call stack for the side by side college-level method to handle.

import java.util.Scanner; import java.io.File;          import java.io.FileNotFoundException;          public form ScannerFromFileWithThrow {    public static void main(Cord[] args)          throws FileNotFoundException          {                                           Scanner in =          new Scanner(new File("test.in"));                                               } }

In this instance, y'all decided not to handle the FileNotFoundException thrown by the Scanner(File) method (with try-catch). Instead, the caller of Scanner(File) - the main() method - declares in its signature "throws FileNotFoundException", which ways that this exception will exist thrown upwardly the call stack, for the next higher-level method to handle. In this case, the side by side college-level method of principal() is the JVM, which simply terminates the program and prints the stack trace.

Point 3: Chief logic is separated from the exception treatment codes

Equally shown in Example ii, the primary logic is contained in the try-cake, while the exception treatment codes are kept in the take hold of-block(due south) separated from the master logic. This greatly improves the readability of the program.

For example, a Java program for file processing could be as follows:

try {        open up file;    procedure file;    ...... } catch (FileNotFoundException ex) {        } grab (IOException ex) {     } finally {   close file;       }

Method Phone call Stack

A typical awarding involves many levels of method calls, which is managed by a then-called method telephone call stack. A stack is a concluding-in-first-out queue. In the following example, master() method invokes methodA(); methodA() calls methodB(); methodB() calls methodC().

1 two 3 4 5 6 vii viii nine 10 11 12 thirteen 14 fifteen 16 17 18 19 twenty 21 22 23 24
public class MethodCallStackDemo {    public static void master(String[] args) {       Organisation.out.println("Enter main()");       methodA();       Organisation.out.println("Exit main()");    }      public static void methodA() {       System.out.println("Enter methodA()");       methodB();       Organization.out.println("Get out methodA()");    }      public static void methodB() {       Organisation.out.println("Enter methodB()");       methodC();       Organization.out.println("Leave methodB()");    }      public static void methodC() {       System.out.println("Enter methodC()");       System.out.println("Exit methodC()");    } }
Enter master() Enter methodA() Enter methodB() Enter methodC() Exit methodC() Exit methodB() Exit methodA() Exit primary()

Exception_MethodCallStack.png

As seen from the output, the sequence of events is:

  1. JVM invoke the principal().
  2. primary() pushed onto call stack, before invoking methodA().
  3. methodA() pushed onto call stack, before invoking methodB().
  4. methodB() pushed onto phone call stack, earlier invoking methodC().
  5. methodC() completes.
  6. methodB() popped out from phone call stack and completes.
  7. methodA() popped out from the phone call stack and completes.
  8. primary() popped out from the call stack and completes. Programme exits.

suppose that we modify methodC() to acquit out a "carve up-by-0" functioning, which triggers a ArithmeticException:

public static void methodC() {    System.out.println("Enter methodC()");    System.out.println(1 / 0);      System.out.println("Get out methodC()"); }

The exception bulletin conspicuously shows the method call stack trace with the relevant argument line numbers:

Enter principal() Enter methodA() Enter methodB() Enter methodC() Exception in thread "master" java.lang.ArithmeticException: / by zero         at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22)         at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16)         at MethodCallStackDemo.methodA(MethodCallStackDemo.coffee:x)         at MethodCallStackDemo.main(MethodCallStackDemo.java:4)

MethodC() triggers an ArithmeticException. As information technology does non handle this exception, it popped off from the call stack immediately. MethodB() also does not handle this exception and popped off the telephone call stack. So does methodA() and chief() method. The main() method passes back to JVM, which abruptly terminates the program and print the call stack trace, equally shown.

Exception & Telephone call Stack

Exception_CallStack.png

When an exception occurs within a Java method, the method creates an Exception object and passes the Exception object to the JVM (in Java term, the method "throw" an Exception). The Exception object contains the type of the exception, and the state of the program when the exception occurs. The JVM is responsible for finding an exception handler to procedure the Exception object. It searches backward through the call stack until information technology finds a matching exception handler for that item class of Exception object (in Java term, information technology is called "take hold of" the Exception). If the JVM cannot find a matching exception handler in all the methods in the call stack, it terminates the program.

This process is illustrated as follows. Suppose that methodD() encounters an abnormal condition and throws a XxxException to the JVM. The JVM searches backward through the call stack for a matching exception handler. It finds methodA() having a XxxException handler and passes the exception object to the handler. Notice that methodC() and methodB() are required to declare "throws XxxException" in their method signatures in social club to compile the plan.

Exception Classes - Throwable, Error, Exception & RuntimeException

The effigy ‎below shows the bureaucracy of the Exception classes. The base class for all Exception objects is java.lang.Throwable, together with its 2 subclasses java.lang.Exception and java.lang.Fault.

Exception_Classes.png

  • The Error class describes internal system errors (e.k., VirtualMachineError, LinkageError) that rarely occur. If such an error occurs, there is little that you can practise and the program will be terminated by the Java runtime.
  • The Exception course describes the error acquired by your plan (e.g. FileNotFoundException, IOException). These errors could exist defenseless and handled past your plan (due east.chiliad., perform an alternating action or do a svelte get out by closing all the files, network and database connections).

Checked vs. Unchecked Exceptions

As illustrated, the subclasses of Mistake and RuntimeException are known every bit unchecked exceptions. These exceptions are not checked by the compiler, and hence, demand non exist caught or declared to exist thrown in your program. This is because there is not much y'all can do with these exceptions. For instance, a "divide by 0" triggers an ArithmeticException, array index out-of-bound triggers an ArrayIndexOutOfBoundException, which are actually programming logical errors that shall be been fixed in compiled-fourth dimension, rather than leaving information technology to runtime exception handling.

All the other exception are chosen checked exceptions. They are checked by the compiler and must be caught or declared to be thrown.

Exception Treatment Operations

Five keywords are used in exception handling: try, catch, finally, throws and throw (have note that in that location is a difference between throw and throws).

Java's exception handling consists of iii operations:

  1. Declaring exceptions;
  2. Throwing an exception; and
  3. Communicable an exception.
Declaring Exceptions

A 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 methodD() is defined every bit follows:

public void methodD()          throws XxxException, YyyException          {     }

The method'due south signature indicates that running methodD() may encounter 2 checked exceptions: XxxException and YyyException. In other words, some of the abnormal conditions within methodD() may trigger XxxException or YyyException.

Exceptions belonging to Fault, RuntimeException and their subclasses need non be declared. These exceptions are called unchecked exceptions because they are not checked past the compiler.

Throwing an Exception

When a Coffee functioning encounters an aberrant situation, the method containing the erroneous argument shall create an advisable Exception object and throw information technology to the Java runtime via the statement "throw XxxException". For instance,

public void methodD()          throws XxxException, YyyException          {           ...    ...        if ( ... )          throw new XxxException(...);              ...        if ( ... )          throw new YyyException(...);              ... }

Note that the keyword to declare exception in the method'south signature is "throws" and the keyword to throw an exception object within the method'south body is "throw".

Communicable an Exception

When a method throws an exception, the JVM searches astern through the phone call stack for a matching exception handler. Each exception handler can handle one particular form of exception. An exception handler handles a specific form can also handle its subclasses. If no exception handler is establish in the telephone call stack, the program terminates.

For instance, suppose methodD() declares that it may throw XxxException and YyyException in its signature, as follows:

public void methodD()          throws XxxException, YyyException          { ...... }

To use methodD() in your plan (says in methodC()), you tin can either:

  1. Wrap the call of methodD() inside a try-grab (or try-grab-finally) as follows. Each catch-cake can contain an exception handler for one type of exception.
    public void methodC() {      ......              try {              ......                     methodD();              ......              } catch (XxxException ex) {                     ......              } grab (YyyException ex} {                     ......              } finally {                            ......              }              ...... }
  2. Suppose that methodC() who calls methodD() does not wish to handle the exceptions (via a try-catch), it can declare these exceptions to be thrown up the telephone call stack in its signature every bit follows:
    public void methodC()              throws XxxException, YyyException              {       ...                  methodD();                  ... }
    In this case, if a XxxException or YyyException is thrown past methodD(), JVM volition terminate methodD() as well as methodC() and pass the exception object up the call stack to the caller of methodC().

endeavour-grab-finally

The syntax of endeavor-catch-finally is:

          attempt {              ......          } catch (          Exception1 ex          ) {              ......          } take hold of (          Exception2 ex          ) {              ......          } finally {                  ......          }        

If no exception occurs during the running of the endeavour-cake, all the catch-blocks are skipped, and finally-block will be executed later on the try-block. If one of the statements in the try-block throws an exception, the Coffee runtime ignores the remainder of the statements in the attempt-cake, and begins searching for a matching exception handler. It matches the exception blazon with each of the take hold of-blocks sequentially. If a grab-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-cake are then executed after that grab-block. The programme continues into the side by side statement after the try-grab-finally, unless information technology is pre-maturely terminated or branch-out.

If none of the catch-block matches, the exception will be passed up the phone call stack. The electric current method executes the finally clause (if any) and popped off the phone call stack. The caller follows the same procedures to handle the exception.

The finally cake is virtually sure to exist executed, regardless of whether or not exception occurs (unless JVM encountered a severe error or a System.exit() is chosen in the catch block).

Example 1
one 2 three 4 5 six 7 8 9 ten xi 12 thirteen 14 15 16 17 18 19 20
import coffee.util.Scanner; import java.io.File; import coffee.io.FileNotFoundException; public course TryCatchFinally {    public static void main(Cord[] args) {       try {                   System.out.println("Start of the main logic");          Organization.out.println("Try opening a file ...");          Scanner in = new Scanner(new File("test.in"));          System.out.println("File Found, processing the file ...");          System.out.println("Terminate of the main logic");       } catch (FileNotFoundException ex) {              Organisation.out.println("File Non Constitute caught ...");       } finally {             System.out.println("finally-block runs regardless of the state of exception");       }              Organisation.out.println("After try-catch-finally, life goes on...");    } }

This is the output when the FileNotFoundException triggered:

Start of the primary logic Try opening a file ... File Not Constitute caught ... finally-block runs regardless of the country of exception Subsequently try-catch-finally, life goes on...

This is the output when no exception triggered:

Start of the main logic Effort opening a file ... File Found, processing the file ... Stop of the main logic finally-cake runs regardless of the state of exception After try-catch-finally, life goes on...
Example 2
1 2 3 4 five half-dozen vii 8 9 10 eleven 12 13 14 xv 16 17 18 xix xx
public grade MethodCallStackDemo {    public static void main(Cord[] args) {       System.out.println("Enter main()");       methodA();       System.out.println("Go out principal()");    }      public static void methodA() {       System.out.println("Enter methodA()");       effort {          System.out.println(1 / 0);                                              } finally {          Organisation.out.println("finally in methodA()");       }       Arrangement.out.println("Leave methodA()");    } }
Enter chief() Enter methodA() finally in methodA() Exception in thread "main" coffee.lang.ArithmeticException: / past zero         at MethodCallStackDemo.methodA(MethodCallStackDemo.coffee:eleven)         at MethodCallStackDemo.primary(MethodCallStackDemo.coffee:4)
endeavour-grab-finally
  • A try-block must be accompanied by at to the lowest degree one catch-block or a finally-block.
  • You can have multiple catch-blocks. Each catch-block catches only one type of exception.
  • A catch block requires one statement, which is a throwable object (i.e., a subclass of java.lang.Throwable), as follows:
    catch (AThrowableSubClass              aThrowableObject) {     }
  • You can employ the post-obit methods to retrieve the type of the exception and the state of the program from the Throwable object:
    • printStackTrace(): Prints this Throwable and its call stack trace to the standard fault stream System.err. The starting time line of the outputs contains the result of toString(), and the remaining lines are the stack trace. This is the nearly common handler, if in that location is naught better that you tin do. For instance,
      try {    Scanner in = new Scanner(new File("test.in"));        ...... } catch (FileNotFoundException ex) {                  ex.printStackTrace();                  }
      You can likewise use printStackTrace(PrintStream s) or printStackTrace(PrintWriter southward).
    • getMessage(): Returns the bulletin specified if the object is constructed using constructor Throwable(Cord message).
    • toString(): Returns a short description of this Throwable object, consists of the name of the class, a colon ':', and a message from getMessage().
  • A catch block communicable a specific exception class can also catch its subclasses. Hence, take hold of(Exception ex) {...} catches all kinds of exceptions. However, this is not a proficient practice as the exception handler that is as well general may unintentionally catches some subclasses' exceptions information technology does not intend to.
  • The order of catch-blocks is important. A bracket must be caught (and placed in front) before its superclass. Otherwise, yous receive a compilation error "exception XxxException has already been caught".
  • The finally-block is meant for cleanup code such equally endmost the file, database connection regardless of whether the effort block succeeds. The finally block is ever executed (unless the catch-block pre-maturely terminated the current method).
What if I really don't care virtually the exceptions

Certainly not appropriate other than writing toy programs. Merely to featherbed the compilation error letters triggered by methods declaring unchecked exceptions, you could declare "throws Exception" in your main() (and other methods), as follows:

public static void principal(String[] args)            throws Exception          {      Scanner in = new Scanner(new File("test.in"));       ......     }
Overriding and Overloading Methods

An overriding method must take the same argument list and return-blazon (or bracket of its original from JDK 1.5). An overloading method must take different argument listing, but it tin can have whatsoever render-type.

An overriding method cannot have more than restricted access. For example, a method with protected access may be overridden to accept protected or public access but not private or default access. This is considering an overridden method is considered to exist a replacement of its original, hence, information technology cannot be more restrictive.

An overriding method cannot declare exception types that were non alleged in its original. However, it may declare exception types are the same every bit, or subclass of its original. It needs not declare all the exceptions as its original. It tin throw fewer exceptions than the original, only not more than.

An overloading method must be differentiated past its argument list. It cannot exist differentiated by the return-type, the exceptions, and the modifier, which is illegal. It can have any render-type, access modifier, and exceptions, every bit long as it can be differentiated by the argument listing.

Mutual Exception Classes

ArrayIndexOutOfBoundsException: thrown by JVM when your code uses an array alphabetize, which is is outside the array's premises. For instance,

int[] anArray = new int[3]; Organization.out.println(anArray[3]);
Exception in thread "main" coffee.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 "master" java.lang.NullPointerException

NumberFormatException: Thrown programmatically (eastward.1000., by Integer.parseInt()) when an endeavor is made to catechumen a string to a numeric blazon, but the string does not have the appropriate format. For example,

Integer.parseInt("abc");
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"

ClassCastException: thrown past JVM when an attempt is made to bandage an object reference fails. For example,

Object o = new Object(); Integer i = (Integer)o;
Exception in thread "principal" java.lang.ClassCastException: coffee.lang.Object cannot exist cast to java.lang.Integer

IllegalArgumentException: thrown programmatically to indicate that a method has been passed an illegal or inappropriate statement. You could re-use this exception for your own methods.

IllegalStateException: thrown programmatically when a method is invoked and the programme is not in an advisable land for that method to perform its task. This typically happens when a method is invoked out of sequence, or perchance a method is only allowed to be invoked once and an attempt is made to invoke information technology again.

NoClassDefFoundError: thrown by the JVM or class loader when the definition of a class cannot exist establish. Prior to JDK 1.7, you volition see this exception telephone call stack trace if you try to run a non-existent class. JDK 1.7 simplifies the fault bulletin to "Error: Could not discover or load main form xxx".

Creating Your Own Exception Classes

Yous should endeavor to reuse the Exception classes provided in the JDK, e.g., IndexOutOfBoundException, ArithmeticException, IOException, and IllegalArugmentException. But you lot can always create y'all own Exception classes by extending from the course Exception or one of its subclasses.

Note that RuntimeException and its subclasses are not checked by the compiler and need not be declared in the method's signature. Therefore, apply them with care, as you will not be informed and may not be aware of the exceptions that may occur by using that method (and therefore practise not have the proper exception handling codes) – a bad software technology practice.

Case
1 2 3 4 v 6
                    public class MyMagicException                  extends Exception                  {    public MyMagicException(Cord message) {         super(message);    } }
one 2 iii 4 5 6 7 8 9 x 11 12 thirteen 14 fifteen sixteen 17 xviii 19
public form MyMagicExceptionTest {        public static void magic(int number) throws MyMagicException {       if (number == 8) {          throw (new MyMagicException("you hit the magic number"));       }       System.out.println("hullo");      }        public static void main(String[] args) {       endeavour {          magic(9);             magic(8);          } catch (MyMagicException ex) {             ex.printStackTrace();       }    } }

The output is as follows:

hello MyMagicException: yous hitting the magic number         at MyMagicExceptionTest.magic(MyMagicExceptionTest.coffee:6)         at MyMagicExceptionTest.primary(MyMagicExceptionTest.java:14)

Assertion (JDK one.4)

JDK 1.four introduced a new keyword called assert, to back up the then-called exclamation feature. Assertion enables yous to test your assumptions well-nigh your program logic (such as pre-conditions, mail service-weather condition, and invariants). Each assertion contains a boolean expression that you believe volition exist true when the program executes. If it is non true, the JVM will throw an AssertionError. This mistake signals you that y'all have an invalid supposition that needs to be fixed. Assertion is much improve than using if-else statements, as it serves equally proper documentation on your assumptions, and information technology does non bear performance liability in the product environment (to exist discussed later).

The assert statement has two forms:

          assert          booleanExpr          ;          assert          booleanExpr          :          errorMessageExpr          ;        

When the runtime execute the exclamation, it kickoff evaluates the booleanExpr . If the value is true, nothing happens. If it is false, the runtime throws an AssertionError, using the no-argument constructor (in the offset form) or errorMessageExpr as the argument to the constructor (in the 2nd class). If an object is passed as the errorMessageExpr , the object's toString() will exist called to obtain the bulletin string.

Exclamation is useful in detecting bugs. It besides serves to document the inner workings of you program (eastward.g., pre-conditions and post-conditions) and enhances the maintainability.

1 good candidate for exclamation is the switch-case argument where the programmer believes that one of the cases will exist selected, and the default-case is not plausible. For example,

ane 2 3 4 5 half dozen vii 8 9 x 11 12 thirteen 14
public class AssertionSwitchTest {    public static void master(String[] args) {       char operator = '%';                         int operand1 = 5, operand2 = 6, outcome = 0;       switch (operator) {          case '+': outcome = operand1 + operand2; break;          case '-': result = operand1 - operand2; break;          instance '*': result = operand1 * operand2; break;          example '/': effect = operand1 / operand2; break;                  default: assert false : "Unknown operator: " + operator;                         }       Organization.out.println(operand1 + " " + operator + " " + operand2 + " = " + result);    } }

Assertion, past default, are disabled to ensure that they are not a performance liability in the product surroundings. To enable assertion, use the runtime command-line pick –enableassertions (or –ea).

In the above instance, "assert simulated" e'er triggers an AssertionError. However, the output is dissimilar, depending on whether assertion is enabled or disabled.

> javac AssertionSwitchTest.java    > coffee          -ea          AssertionSwitchTest             
Exception in thread "principal" java.lang.AssertionError: %         at AssertionSwitchTest.main(AssertionSwitchTest.java:eleven)
> java AssertionSwitchTest        
5 % 6 = 0

In the higher up instance, since the "affirm false" always triggers an AssertionError, you could choose to throw an AssertionError. "throw" is always enabled during runtime.

default: throw new AssertionError("Unknown operator: " + operator);

Another usage of assertion is to affirm "internal invariants". In other words, to assert the possible values of an internal variable. For example,

one 2 3 iv 5 half dozen vii 8 9
public class AssertionTest {    public static void main(Cord[] args) {       int number = -5;                             affirm (number >= 0) : "number is negative: " + number;                                           Organization.out.println("The number is " + number);    } }
> java          -ea          AssertionSwitchTest        
Exception in thread "chief" coffee.lang.AssertionError: -5         at AssertionTest.primary(AssertionTest.coffee:5)

Assertion tin can be used for verifying:

  • Internal Invariants: Assert that a value is within a certain constraint, e.thousand., assert 10 > 0.
  • Class Invariants: Assert that an object'southward state is within a constraint. What must be true almost each instance of a form earlier or after the execution of a method? Class invariants are typically verified via private boolean method, due east.thousand., an isValid() method to cheque if a Circle object has a positive radius.
  • Control-Period Invariants: Assert that a certain location will not be reached. For example, the default clause of a switch-case statement.
  • Pre-conditions of methods: What must exist truthful when a method is invoked? Typically expressed in terms of the method's arguments or united states of america of its objects.
  • Post-conditions of methods: What must be true after a method completes successfully?
Pre-conditions of public methods

Assertion should not exist used to check the validity of the arguments (pre-status) passed into "public" method. It is considering public methods are exposed and anyone could phone call this method with an invalid argument. Instead, use a if statement to check the argument and throw an IllegalArgumentException otherwise. On the other hand, private methods are under your sole command and it is appropriate to assert the pre-atmospheric condition. For example,

            public Time(int hr, int minute, int 2d) {    if(hour < 0 || hour > 23 || infinitesimal < 0 || minute > 59 || second < 0 || 2d > 59) {       throw new IllegalArgumentException();    }    this.hour = hour;    this.minute = minute;    this.second = second; }
Example

[TODO] Example on pre-condition (private method), postal service-condition, and class invariant.

LINK TO Coffee REFERENCES & RESOURCES

harmonfluntence.blogspot.com

Source: https://www3.ntu.edu.sg/home/ehchua/programming/java/j5a_exceptionassert.html

0 Response to "Java Throw Exception Example and Then Ask Again"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel