- BASICS
- Classes
- Objects
- Arrays
- Variables
- Loops
- Numbers
- Strings
-
Exceptions
- Regexp
- OOP
- Inheritance
- Polymorphism
- Static Keyword
- Abstract Keyword
- Interfaces
- Constructors
- Packages
- Nested Classes
- Final Keyword
- SWING
- Frame
- Panel
- Listener
- Combo Box
- Label
- Image
- Menu
- Table
- Layout
- Drawing
- Timer
- Designer
- COLLECTIONS
- Lists
- Comparable
- Sets
- Maps
- Generics
- Properties
- Streams
- Json
- COMPILER
- Sublime Text
- Apache Ant
- I/O
- Streams IO
- Socket
- Watching Files
- Logger
- Clipboard
- Encrypt
- JAVAFX
- Openjfx
- Scene Builder
- First App
- Jar Archive
- On Action
- Change Listener
Throws
The developer is forced to wrap the code with try/catch.
/**
* Throws Exception
*
* Using throws Exception forces the developer ...
* to wrap the code with try/catch
* She will know that you are using a risky method
*/
package com.minte9.basics.exceptions;
public class Throws {
public static void main(String[] args) {
try {
A.check("correct");
A.check("wrong"); // OK for compiler
} catch (Exception e) {
System.out.print(
"Exception: " + e.getMessage() // Exception: Wrong value!
);
}
}
}
class A {
static boolean check(String s) throws Exception { // Look Here
if (s.equals("wrong")) {
throw new Exception("Wrong value!");
}
return true;
}
}
Multiple
A method can throw multiple exceptions.
/**
* Multiple exceptions
*
* A method can throw multiple exceptions
* Declare it, when you don't want to handle an exception
* The code inside finally block is always executed
*/
package com.minte9.basics.exceptions;
public class Multiple {
public static void main(String[] args)
throws NullPointerException { // Look Here
try {
test(-10); // Positive number required!
System.out.println(args[2]); // Index 2 out of bounds!
} catch (ArrayIndexOutOfBoundsException ex) { // Look Here
System.out.println(ex.getMessage());
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
System.out.println("Always executed!");
}
}
public static void test(int n)
throws Exception, ArrayIndexOutOfBoundsException {
if (n < 0) {
throw new Exception("Positive number required");
}
}
}
Last update: 531 days ago