Kotlinlearncs.online LogoJava

    ← Prev

    Index

    Next →

    Kotlin
    Java
    • Working with Exceptions : 38

    • Throwing Exceptions : 37

    • Catching Exceptions : 36

    • References and Polymorphism : 35

    • References : 34

    • Data Modeling 2 : 33

    • Equality and Object Copying : 32

    • Polymorphism : 31

    • Inheritance : 30

    • Data Modeling 1 : 29

    • Static : 28

    • Encapsulation : 27

    • Constructors : 26

    • Objects, Continued : 25

    • Introduction to Objects : 24

    • Compilation and Type Inference : 23

    • Practice with Collections : 22

    • Maps and Sets : 21

    • Lists and Type Parameters : 20

    • Imports and Libraries : 19

    • Multidimensional Arrays : 18

    • Practice with Strings : 17

    • null : 16

    • Algorithms and Strings : 15

    • Strings : 14

    • Functions and Algorithms : 13

    • Practice with Functions : 12

    • More About Functions : 11

    • Errors and Debugging : 10

    • Functions : 9

    • Practice with Loops and Algorithms : 8

    • Algorithms I : 7

    • Loops : 6

    • Arrays : 5

    • Compound Conditionals : 4

    • Conditional Expressions and Statements : 3

    • Operations on Variables : 2

    • Variables and Types : 1

    • Hello, world! : 0

    Throwing Exceptions

    public class Container {
    int[] values;
    public Container(int setSize) {
    if (setSize <= 0) {
    throw new IllegalArgumentException("Container size must be positive");
    }
    values = new int[setSize];
    }
    }
    Container good = new Container(8);
    Container ohnoes = new Container(-1);

    Next we’ll continue exploring Java exceptions. First, we’ll look at how we can throw our own exceptions. Next, we’ll discuss the different types of Java exceptions and how they are used. Aren’t errors fun? Let’s do this.

    throw
    throw

    Last time we looked at try-catch, Java’s syntax for handling exceptions. But where do exceptions come from?

    Some exceptions are generated directly by Java. For example, executing this code will generate a NullPointerException:

    Object o = null;
    System.out.println(o.hashCode());

    However, Java also provides a way for us to throw exceptions directly—the throw keyword! Let’s see how that works.

    // throw

    When to throw
    When to throw

    Java has several built-in exceptions that you may find useful in your own code. throw is particularly useful when there is no valid way to continue. Maybe your method has received bad input, or encounters a situation that it is unprepared to handle. We’ll discuss this more in future lessons.

    As a initial example, many of the situations that we’ve been handling using assert are better handled using the IllegalArgumentException. Let’s look at an example:

    // When to throw

    Solve: Return an Exception (Practice)

    Created By: Geoffrey Challen
    / Version: 2020.11.0

    Create a public class called Exceptioner that provides one static method exceptionable. exceptionable accepts a single int as a parameter. You should assert that the int is between 0 and 3, inclusive.

    If the int is 0, you should return an IllegalStateException. If it's 1, you should return a NullPointerException. If it's 2, you should return a ArithmeticException. And if it's 3, you should return a IllegalArgumentException.

    Exception Types
    Exception Types

    In Java the Throwable class is the superclass of all objects that can be thrown, either using throw or in case of an error like a null pointer exception. Throwable has three important subclasses that are handled differently in Java: checked exceptions, unchecked exceptions, and errors.

    Let’s look at each category in turn. First, let’s browse the documentation together!

    Checked Exceptions
    Checked Exceptions

    Checked exceptions in Java must be handled. The compiler will check and enforce this! They are always generated using throw, which is how the compiler knows where they are and when you need to handle them.

    The Exception class itself is checked, as are most of its descendants. Let’s see a example of checked examples.

    (Note that this example uses a playground that works a bit differently than the ones that we’ve used previously. I’ll explain why in the walkthrough.)

    public class Main {
    public static void main() {
    // Checked exceptions
    }
    }

    Unchecked Exceptions
    Unchecked Exceptions

    Unchecked exceptions don’t need to be handled. But, the reason for this is that, in many cases, they arise from programmer error. Let’s look at some examples.

    public class Main {
    public static void main() {
    // Checked exceptions
    }
    }

    Errors
    Errors

    The final category are Java errors. These are serious problems that you should not try to handle. According to the documentation:

    An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

    However, it is worth noting that assert generates an error. It is also possible to generate errors through programming errors, like this one:

    int add(int value) {
    return add(value);
    }
    System.out.println(add(1));

    This generates a StackOverflowError. You may get much more familiar with this kind of error soon…

    Solve: Restaurant Capacity Manager

    Created By: Geoffrey Challen
    / Version: 2021.9.0

    Create a class CapacityManager to manage restaurant dining capacity. You should provide a public constructor that allows the capacity of the restaurant to be set as an int when the CapacityManager is created. You don't need to provide either a getter or a setter for the capacity, which will not change.

    Provide two methods: enter and leave. Each accepts a count of guests (as an int) that are either arriving (enter) or departing (leave) from the restaurant. Both should return the number of guests after the operation completes as an int. If the count is negative or zero, both methods should throw an IllegalArgumentException. enter should also throw a IllegalStateException if the new party would exceed the capacity of the restaurant. This restaurant also refuses to admit parties larger than 8, and if one arrives enter should throw a PartyTooLarge exception, which you can create without importing:

    Note that this is a checked exception!

    leave should also throw an IllegalStateException if a party leaves that is larger than 8, or if the leave would cause the number of diners to fall below zero, since both represent mistakes in our enter code.

    In both enter and leave, if an exception is thrown, the number of diners should not be changed.

    When you are finished, here is how your class should work:

    Do not use assert to solve this problem! Now that we know how to throw exceptions, we'll utilize that ability in many of the places that we used assert previously.

    CS People: Timnit Gebru
    CS People: Timnit Gebru

    Timnit Gebru’s is the co-founder of Black in AI and the founder of the Distributed Artificial Intelligence Research Institute. Her work identifying bias in artificial intelligence and leadership drawing attention to ethical issues in AI prompted her abrupt departure from Google, specifically due to work that she and co-authors hoped to publish drawing attention to weaknesses and biases inherent in large langauge models. That work seems even more relevant today, with the rise of GPT-3, ChatGPT, and the growing use of large language models in other contexts and for a wide variety of purposes.

    In the video below, she discusses one component of her work, specifically improving the understanding of the datasets used to train and generate AI models:

    More Practice

    Need more practice? Head over to the practice page.