Computer Science

Java Throw

Java Throw is a keyword used in Java programming language to explicitly throw an exception. It is used to indicate that an error has occurred and the program cannot continue executing normally. The throw statement is followed by an object that represents the exception being thrown.

Written by Perlego with AI-assistance

8 Key excerpts on "Java Throw"

  • Book cover image for: OCP Oracle Certified Professional Java SE 11 Programmer I Study Guide
    • Jeanne Boyarsky, Scott Selikoff(Authors)
    • 2019(Publication Date)
    • Sybex
      (Publisher)
    ArrayIndexOutOfBoundsException since the array has no elements. That means questions about exceptions can be hidden in questions that appear to be about something else.
     On the exam, many questions have a choice about not compiling and about throwing an exception. Pay special attention to code that calls a method on a null reference or that references an invalid array or List index. If you spot this, you know the correct answer is that the code throws an exception at runtime.
    The second way for code to result in an exception is to explicitly request Java to throw one. Java lets you write statements like these:
    throw new Exception(); throw new Exception("Ow! I fell."); throw new RuntimeException(); throw new RuntimeException("Ow! I fell.");
    The throw keyword tells Java you want some other part of the code to deal with the exception. This is the same as the young girl crying for her daddy. Someone else needs to figure out what to do about the exception.
    throw vs. throws
    Anytime you see throw or throws on the exam, make sure the correct one is being used. The throw keyword is used as a statement inside a code block to throw a new exception or rethrow an existing exception, while the throws keyword is used only at the end of a method declaration to indicate what exceptions it supports. On the exam, you might start reading a long class definition only to realize the entire thing does not compile due to the wrong keyword being used.
    When creating an exception, you can usually pass a String parameter with a message, or you can pass no parameters and use the defaults. We say usually because this is a convention. Someone could create an exception class that does not have a constructor that takes a message. The first two examples create a new object of type Exception and throw it. The last two show that the code looks the same regardless of which type of exception you throw.
    Additionally, you should know that an Exception is an Object
  • Book cover image for: Developing Java Software
    • Russel Winder, Graham Roberts(Authors)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    Instead, they are caused by an event occurring that was either unexpected or outside the range of conditions the program was designed to work with. Handling user input is often a source of run-time errors, as users make mistakes in the data they are entering. For example, a user can provide an incorrect file name, so the program fails to open a file. Run-time errors and some logic errors are the sources of exceptions—unexpected events that are not algorithm failures that cause a program to fail. Exceptions that are not handled are undesirable as, by default, at least in Java, the program will terminate and not complete what it is doing. This can often result in a loss of data and is very annoying to the user of the program. Ideally, if an error occurs, we want to be able to recover the situation and enable the program to carry on. If that is not possible, the program should at least terminate in a safe and tidy way, preserving any data that would otherwise be lost. In Java, exceptions are represented by objects. This allows information about what happened to cause an exception, and where in the source code the exception happened, to be easily transferred around a program. 8.3 Representing Exceptions tip Ideally, a properly designed and tested program should never terminate unexpectedly. Even if it is not possible to carry on, important data should be saved, so that it can be recovered next time the program is run. 8.4 Throwing an Exception 273 The Java class libraries provide a number of exception classes, all of which are direct or indirect subclasses of the class Throwable. Most exceptions that are handled are represented by classes that are subclasses of class Exception, a subclass of Throwable.
  • Book cover image for: An Object-Oriented Approach to Programming Logic and Design
    Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. When you learn a programming language, you will learn about subclasses of Exception that you might want to use in your code. For example, you saw in Figure 10-2 that in Java, an ArithmeticException is created automatically. Therefore, in the code in Figure 10-5, you could catch a more specific ArithmeticException instead of the more general Exception . If the division-by-0 error occurs in Figure 10-5, an Exception object is created automatically and thrown to the catch block. The programmer did not have to write a throw statement; the throw operation occurred implicitly. Later in this chapter, you will see methods in which the programmer explicitly throws an exception. In this application, the try block and its throw operation reside in the same method as the catch block. This is not much different from including an if … else pair to handle the mistake. Later in this chapter, you will learn that try blocks, throw statements, and their corresponding catch blocks frequently reside in separate methods, which increases the client ’ s flexibility in error handling. In the method in Figure 10-5, the parameter mistake in the catch block is an object of type Exception . The object is not used within this catch block, but it could be. For example, depending on the language, the Exception class might contain a method named getMessage() that returns a string with details about the cause of the error. In that case, you could place a statement such as the following in the catch block: output mistake.getMessage() The message generated by this built-in method would be similar to / by zero . As you will recall from the Java example in Figure 10-2, this message is generated when exception handling occurs automatically. Watch the video Throwing and Catching an Exception .
  • Book cover image for: C++ Programming
    eBook - PDF

    C++ Programming

    From Problem Analysis to Program Design

    Rethrowing and Throwing an Exception When an exception occurs in a try block, control immediately passes to one of the catch blocks. Typically, a catch block either handles the exception or partially pro- cesses the exception and then rethrows the same exception, or it rethrows another exception in order for the calling environment to handle the exception. The catch block in Examples 14-4 through 14-14 handles the exception. The mechanism of rethrowing or throwing an exception is quite useful in cases in which a catch block catches the exception but cannot handle the exception, or if the catch block decides that the exception should be handled by the calling block or environment. This allows the programmer to provide the exception-handling code all in one place. To rethrow or throw an exception, we use the throw statement. The general syntax to rethrow an exception caught by a catch block is (in this case, the same exception is rethrown) or in which expression is a constant value, variable, or object. The object being thrown can be either a specific object or an anonymous object. A function specifies the exceptions it throws (to be handled somewhere) in its heading using the throw clause. For example, the following function specifies that it throws exceptions of type int, string, and divisionByZero, in which divisionByZero is the class, as defined previously. void expThrowExcep(int x) throw (int, string, divisionByZero) { . . . //include the appropriate throw statements . . . } The program in Example 14-15 further explains how a function specifies the excep- tion it throws. throw; throw expression; Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience.
  • Book cover image for: Java Programming
    eBook - PDF
    TWO TRUTHS & A LIE Specifying the Exceptions that a Method Can Throw 1. Exception specification is the practice of listing possible exceptions in a throws clause in a method header. 2. Many exceptions never have to be explicitly thrown or caught, nor do you have to include a throws clause in the headers of methods that automatically throw these exceptions. 3. If you write a method with a throws clause for a checked exception in the header, then any method that uses your method must catch and handle the possible exception. Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 601 Tracing Exceptions Through the Call Stack where the computer stores the list of memory locations to which the system must return when methods end. Programmers sometimes refer to the call stack as the execution stack, the memory stack, or just the stack. When a method throws an exception and the method does not catch it, the exception is thrown to the next method up the call stack, or in other words, to the method that called the offending method. Figure 12-32 shows how the call stack works. If methodA() calls methodB(), and methodB() calls methodC(), and methodC() throws an exception, Java first looks for a catch block in methodC(). If none exists, Java looks for the same thing in methodB(). If methodB() does not have a catch block, Java looks to methodA(). If methodA() cannot catch the exception, it is thrown to the Java Virtual Machine, which displays a message at the command prompt. For example, examine the application in Figure 12-33.
  • Book cover image for: OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide
    • Jeanne Boyarsky, Scott Selikoff(Authors)
    • 2014(Publication Date)
    • Sybex
      (Publisher)
    Throwable .
    Figure 6.1
    Categories of exception
    Error means something went so horribly wrong that your program should not attempt to recover from it. For example, the disk drive “disappeared.” These are abnormal conditions that you aren't likely to encounter.
    A
    runtime exception
    is defined as the RuntimeException class and its subclasses. Runtime exceptions tend to be unexpected but not necessarily fatal. For example, accessing an invalid array index is unexpected. Runtime exceptions are also known as unchecked exceptions.

    Runtime vs. at the Time the Program is Run

    A runtime (unchecked) exception is a specific type of exception. All exceptions occur at the time that the program is run. (The alternative is compile time, which would be a compiler error.) People don't refer to them as run time exceptions because that would be too easy to confuse with runtime! When you see runtime, it means unchecked.
    A
    checked exception
    includes Exception and all subclasses that do not extend RuntimeException . Checked exceptions tend to be more anticipated—for example, trying to read a file that doesn't exist.
    Checked exceptions? What are we checking? Java has a rule called the
    handle or declare rule
    . For checked exceptions, Java requires the code to either handle them or declare them in the method signature.
    For example, this method declares that it might throw an exception: void fall() throws Exception { throw new Exception(); }
    Notice that you're using two different keywords here. throw tells Java that you want to throw an Exception . throws simply declares that the method might throw an Exception . It also might not. You will see the throws
  • Book cover image for: Programming Fundamentals Using JAVA
    No longer available |Learn more

    Programming Fundamentals Using JAVA

    A Game Application Approach

    They are not caused by programming errors, an I/O error, or something that can be dealt with within an application. When they do occur, they are best processed by the Java Runtime environment, the catcher of all uncaught exceptions. Runtime errors that generate checked exceptions are considered to be situations that can be dealt with by a method within an application and are serious enough that the translator requires that they either are dealt with or that the method indicates that it is intentionally ignoring the error via a throws clause. Errors that cause instances of the class RunTimeError or its descendants to be thrown are considered errors that will be eliminated during the testing phase of the application’s development, and therefore, the translator does not require that the application process these errors or indicate that they are intentionally being ignored via a throws clause. In situations where the programmer feels that erroneous input or other non-programming error-related events could cause these unchecked exception objects to be thrown, a try-catch construct should be included in the portions of the application where these events could occur. 10.3 PROCESSING THROWN EXCEPTIONS Exceptions are processed using a try-catch construct. The construct consists of a try clause that is immediately followed by a catch clause. The statements associated with each of these clauses are always enclosed in a set of brackets, even if there is only one statement associated with them. For this reason, they are commonly referred to as try and catch blocks. The try block is used to detect thrown exceptions, and the catch block is used to process the errors that produced the exceptions. As illustrated in Figure 10.2, one try block can be followed by multiple catch blocks, and the catch blocks must immediately follow the try block. Coding statements in between any of the blocks is a syntax error
  • Book cover image for: Java 2 For Dummies
    • Barry Burd(Author)
    • 2004(Publication Date)
    • For Dummies
      (Publisher)
    299 Chapter 12: Looking Good When Things Take Unexpected Turns bug me about this. Instead of having a try-catch statement, I’m passing the responsibility for acknowledging the exception to the main method (the method that called the takeANap method).” Indeed, in the main method, the call to takeANap is inside a try clause. That try clause has a catch clause with a parameter of type Interrupted Exception. So everything is okay. Method takeANap passes the responsibil- ity to the main method, and the main method accepts the responsibility with an appropriate try-catch statement. Everybody’s happy. Even the Java com- piler is happy. To better understand the throws clause, imagine a volleyball game in which the volleyball is an exception. When a player on the other team serves, that player is throwing the exception. The ball crosses the net and comes right to you. If you pound the ball back across the net, you’re catching the exception. But if you pass the ball to another player, you’re using the throws clause. In essence, you’re saying, “Here, other player. You deal with this exception.” A statement in a method can throw an exception that’s not matched by a catch clause. This includes situations in which the statement throwing the exception isn’t even inside a try block. When this happens, execution of the program jumps out of the method that contains the offending statement. Execution jumps back to whatever code called the method in the first place. A method can name more than one exception type in its throws clause. Just use commas to separate the names of the exception types, like in the follow- ing example: throws InterruptedException, IOException, ArithmeticException The Java API has hundreds of exception types. Several of them are subclasses of the RuntimeException class. Anything that’s a subclass of Runtime Exception (or a sub-subclass, sub-sub-subclass, and so on) is unchecked. Any exception that’s not a descendent of RuntimeException is checked.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.