CodeGym /Java Course /Java Syntax /How exceptions work

How exceptions work

Java Syntax
Level 9 , Lesson 5
Available

"I'd like to tell you a bit about how exceptions work. The example below should give you a rough idea of what happens:"

Code that uses exceptions:
class ExceptionExampleOriginal
{


    public static void main(String[] args)
    {
        System.out.println("main begin");
        try
        {
            System.out.println("main before call");

            method1();



            System.out.println("main after call");
        }
        catch (RuntimeException e)
        {


            String s = e.getMessage();
            System.out.println(s);
        }
        System.out.println("main end");
    }

    public static void method1()
    {
        System.out.println("method1 begin");
        method2();

        System.out.println("method1 end");
    }

    public static void method2()
    {
      System.out.println("method2");
      String s = "Message: Unknown Exception";
      throw new RuntimeException(s);

    }
}
Approximate representation of what happens
public class ExceptionExample
{
    private static Exception exception = null;

   public static void main(String[] args)
    {
        System.out.println("main begin");

       
        System.out.println("main before call");

        method1();

        if (exception == null)
        {
            System.out.println("main after call");
        }
        else if (exception instanceof RuntimeException)
        {
            RuntimeException e = (RuntimeException) exception;
            exception = null;
            String s = e.getMessage();
            System.out.println(s);
        }
        System.out.println("main end");
    }

    public static void method1()
    {
        System.out.println("method1 begin");
        method2();
        if (exception != null) return;
        System.out.println("method1 end");
    }

    public static void method2()
    {
        System.out.println("method2");
        String s = "Message: Unknown Exception";
        exception = new RuntimeException(s);
        return;
    }
}

"I'm totally lost."

"All right. Let me explain what's going on."

"In the example on the left, we call a few methods in succession. In method2, we deliberately create and throw an exception (we create an error)."

"The example on the right shows what is happening."

"Look at method2. Instead of creating an exception, we create a RuntimeException object, save it to the static variable exception, and then immediately exit the method using a return statement."

"In method1, after calling method2, we check whether there is an exception. If there is an exception, then method1 ends at once. A check like this is performed indirectly after every (!) method call in Java."

"Wow!"

"Wow is right."

"In the right column, I've used the main method to show approximately what happens when an exception is caught using a try-catch construct. If there is no exception, then everything continues running as expected. If there is an exception and it is the same type specified in the catch statement, then we handle it."

"What do throw and instanceof mean ?"

"Look at the last line: throw new RuntimeException(s);. This is how you create and throw an exception. We won't work on that yet. It was just an example."

"We use a instanceof B to check whether object a is of type B, i.e. whether the object referenced by the variable exception is a RuntimeException. This is a boolean expression."

"I think I got it. Almost."

9
Task
New Java Syntax, level 9, lesson 5
Locked
URL validation
In this task, you need to perform URL validation. A simple URL scheme looks like this: ://. The checkProtocol(String) method checks the network protocol (http or https) of the URL passed in input parameter and returns the result of this check — the name of the network protocol as a string. And the
9
Task
New Java Syntax, level 9, lesson 5
Locked
Searching in a string
The getIndexOfFirstWord(String, String) method and the getIndexOfLastWord(String, String) method both accept a string and a word. The getIndexOfFirstWord(String, String) method needs to return the index of the first character of the first instance of the word (the second method parameter) in the st
9
Task
New Java Syntax, level 9, lesson 5
Locked
Path update
Implement the changePath(String, String) method so that it replaces the jdk version in the path passed in the first method parameter with the version passed in the second parameter, and returns the new path. The JDK version starts with "jdk" and ends at "/". Example: path - "/usr/java/jdk1.8/bin" J
Comments (13)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
priss Level 18, Roosendaal, Netherlands
12 April 2020
Can anyone explain these lines of codes: else if (exception instanceof RuntimeException) { RuntimeException e = (RuntimeException) exception; exception = null; String s = e.getMessage(); System.out.println(s); }
Daniel Walbolt Level 22, Waterville, United States
22 May 2020
I'm sure you've already explained this to yourself by now, but for anyone else wondering: - 1) the else if checks a condition if the preceding if statement returns false (the previous statement in the picture is checking if there is no exception occurring, but for our case there is) - 2) (exception instanceof RuntimeException) as the lesson explains at the end, is a boolean expression which is just a faster way of comparing two objects by their type (is a Person an Object? If so, return true, if not, return false). So that statement is checking if the exception that WAS THROWN is of TYPE: RuntimeException. - 3) Next they create a RuntimeException object named 'e' and use a cast of (RuntimeException) on exception because that code would not operate if it was not already a RuntimeException. (another exception can come up if you try saying an object is something it is not (int num = (String) anumber;). - 4) exception = null is basically deleting the reference to the exception and marking it for (as we have learned by now) gargage collection. - 5) Then the last two lines are for getting the message of the exception (what is the exception about) and printing it to the console. When the program catches an exception, it removes all references to it so it can be deleted. The reason why they created an object for the exception I would assume is so they don't have a 'volatile" exception on the loose. The faster you get rid of an exception, the better, because it can reek havoc on your program's operations. The object allows the error to be safe.
Anonymous #10756622 Level 13, United States of America
13 August 2021
I have a followup question about 3) and 4); why do you need a type casting when you have already determined exception is an instance of RuntimeException through the else if(exception instanceof RuntimeException); also do you have to create the RuntieException object e? can you do String s = exception.getMessage() without creating e? Many thanks!
Anonymous #10428383 Level 12, Seattle, United States
28 December 2021
"We use a instanceof B to check whether object a is of type B, i.e. whether the object referenced by the variable exception is a RuntimeException. This is a boolean expression." else if (exception instanceof RuntimeException) else if( "a" instanceof "b" ) {do something}
Jonaskinny Level 25, Redondo Beach, United States
20 February 2022
follow-up answers for 3 & 4. 3-this is psuedo-code used by the author to help explain (using code that you would understand from prior lessons) to explain what happens in a catch block (since we are not familiar with the syntax). So you would never code it this way, but yes if you want to cast an Exception to a subclass of Exception, you should check first in case its not an instance of that type, or you would create a ClassCastException in the catch block, where you don't have any means of catching that new ClassCastException (unless you were to code infinate catch blocks) 4-yes you could just use e.getMessage but again this was psuedo-code so it is coded for illustrative purposes rather than any coding recommendation.
Michael Amann Level 22, United States of America, United States
11 May 2022
It's not actually an "else if." The material clearly states this is an approximation of what is happening in the code and the "else if" construction is used to illustrate.
Nikolaos Level 22, Vrontados, Greece
28 August 2019
I 'm lost...
Adrie Taniwidjaja Level 11, Bandung, Indonesia
8 August 2019
what is the meaning of "(RuntimeException) exception" int this declaration: RuntimeException e = (RuntimeException) exception
9 January 2020
type casting!
Kotlet Level 28, Wroclaw, Poland
22 June 2019
And the output of the code is: main begin main before call method1 begin method2 Message: Unknown Exception main end
// Java Poser Level 18, Cincinnati, United States
25 March 2019
Noice!!
Hashirama Level 26, Port-Harcourt, Nigeria
26 January 2019
Am with you Rishi, keep going.
Tayyab Mubeen Level 16, Lahore, Pakistan
21 October 2018
exception handling.....!!!!