Please enable JavaScript.
Coggle requires JavaScript to display documents.
4.Exception Handling, Assertions
and Enumeration (Exception Handling…
4.Exception Handling, Assertions
and Enumeration
Exception Handling
Throwing Exceptions
(the throws
keyword)
This keyword throws checked exceptions
out from the user-defined method and allows the program to compile. Now if exception happens, will be a runtime error instead.
- If there is an API that you are using which throws a certain Exception in its methods, whichever user-defined method invoking that API class requires an additional statement as follows:
public static void main(String[] args) throws
theExceptionName
try
- catch
- finally
Instead of merely throwing exceptions at the user, we should handle them for the user. How? using try-catch-finally blocks.
- In our
try
block, we only put in the business logic of our program.
- If the business logic generates an exception, we need to catch it to handle it. We need to anticipate the exception type and then build a catch block that catches that type of exception.
- Typically, we have a catch block for each type of exception thrown by business logic.
- We can use an optional
finally
block to do house-keeping tasks after handling the exception in catch.
-
Exception control flow
- In our business logic i.e. try block, lets say m1() calls m2() and m2() calls m3(). So without any exception we'd get m1() -> m2() -> m3() -> m2() -> m1() -> finally block.
- However, if m3() throws an exception E and this causes m3() to stop prematurely, the block of code that catches E is searched, beginning at m3(), then back to its caller m2() and then m1(). Since none of the methods catches the exception, the code that handles E in the initial caller i.e. m3(), and is executed in the
catch
block , before executing the finally
block.
Checked and unchecked exceptions
- Hierarchy:
Object
extended by Throwable
, which is extended by Exception
. Children of Exception
are RuntimeException
and OtherException
. Another child of Throwable
is Errors
Checked Exceptions (programmer should actively anticipate and handle)
- All exceptions other than Runtime Exceptions
are known as Checked exceptions as compiler checks them during compilation to see whether programmer has handled them or not. If these exceptions are not handled, you will get a compilation error. Common ones include
- IOException
- ClassNotFoundException
Unchecked Exceptions (usually unanticipated, should be caught (catch
) or propagated (throw
)
- Basically, all unchecked exceptions are Runtime exceptions.
Creating own exceptions
throw
an Exception
- Given the constraints of a problem, if our program does not meet these constraints, then we have an exception scenario. This is where we should
throw
an Exception to the caller. (need a catch block to handle the Exception thrown)
Generating Exception
- We can create our own exceptions by inheriting existing ones.
- we create a class file with the Exception Name and inherit from relevant Exceptions. e.g.
class IllegalCircleException extends IllegalArgumentException
{
The constructor can simply take in a String message argument and invoke super(message);
It also needs a toString() method that basically prints the message. use inherited method getMessage();
- If it has a toString method, you can throw the Exception at the end of the catch block, instead of printing things in catchblock.
- Only create your own exceptions if there is a reason to do so, else just find one that suits your needs.
- When overriding a method that throws a checked exception, the overriding method must throw only the same or more specific exception.
- Although convenient, do not ever catch the parent Exception class.Always handle exceptions at the appropriate level of abstraction.
What is an Exception?
- An unwanted event that interrupts normal flow of the program.
- When an exception occurs, the program execution terminates.
-
Common Reasons for Exceptions:
- Opening non-existent file in program
- Network connection problem
- bad input data provided by user
-
Assertions
What are Assertions?
- While exceptions are usually used to handle user mishaps (USER ERRORS), we use
assert
to prevent bugs (PROGRAMMER ERRORS)
- When implementing a program, it is useful to state conditions that should be true at a particular point,.These conditions are called ASSERTIONS.
-
-
Syntax for assert statements:
-
assert expression
;
-
assert expression1 : expression2;
(if expression1, the assertion, is false, execute expression2) //this one is more useful because you can return a string in expression2 and terminal prints it out when generating the exception message. DONT PRINT IN EXPRESSION2. JUST RETURN STRING, don't need return keyword.
Also need to run the program with the -ea
flag before Class Name else assertions are not enabled
Enumeration
Java enum
types
How to define?enum EventType {
ARRIVE,
SERVE,
WAIT,
DONE,
LEAVE
}
- What the above does is it declares a new type, called
EventType so now if you get current state of event, check if it == EventType.ARRIVE. So you have 5 constants now, ARRIVE, SERVE, WAIT, DONE and LEAVE. So now, when assigning events with states, assign them like this: EventType state = EventType.ARRIVES etc.
enum's fields and methods:
- Each constant of an enum type is an instance of enum class and is a field declared with public static final implicitly, so don't need to redefine. If someone uses enum with private non-static or non-final, compiler will throw error.
- Constructors, emthods and fields can be defined in enums.
-