Java Do While Try Catch Throw Exception Continue
<< Back to JAVA
Java Exceptions: try, catch and finally
Use exception handling with the try and catch statements. Handle different Exception classes.
Exceptions. In programs, errors happen. Exceptions help us deal with them. These use an alternative control flow. The program's main control flow terminates and exception handling begins.
Try, catch. Developers use the try and catch keywords to handle exceptions. When an error occurs, a catch block is located and run. The program then continues.
An example. A catch clause that matches an Exception will catch any kind of exception. This is the simplest way to catch any exception.
Step 1: We cause an exception on purpose—we divide by zero. This statement is inside a try block.
Step 2: The ArithmeticException, derived from Exception, is matched by the Exception catch clause. We then display the exception.
Note: In this example, the Exception base class is used. The exception is of type ArithmeticException.
Java program that uses try, catch public class Program { public static void main(String[] args) {
try { // Step 1: divide by zero. int value = 1 / 0; }
catch (Exception ex) { // Step 2: display exception. System.out.println(ex); } } } Output java.lang.ArithmeticException: / by zero
NullPointerException. Exceptions often occur when we do not expect them. This program appears correct. It compiles. But when we use length() on a null string, a NullPointerException occurs.length
Java program that causes NullPointerException public class Program { public static void main(String[] args) { // An input string. String name = "sam"; System.out.println(name.length()); // When string is null, an exception occurs. name = null; System.out.println(name.length()); } } Output 3 Exception in thread "main" java.lang.
NullPointerException at program.Program.main(Program.java:9) Java Result: 1
Unhandled exception. A method that is known to throw an exception must have a "throws" clause in its declaration. An unresolved compilation program (java.lang.Error) otherwise occurs.
Program 1: We see a program that fails compilation. It cannot be executed. A java.lang.Error is reported.
Program 2: This program adds the "throws Exception" clause. It now executes correctly—it throws the Exception during runtime.
Java program that causes compilation error public class Program { public static void main(String[] args) {
throw new Exception(); } } Output Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type Exception at program.Program.main(Program.java:5) Java program that has no compilation error public class Program { public static void main(String[] args) throws Exception {
throw new Exception(); } } Output Exception in thread "main" java.lang.Exception at program.Program.main(Program.java:5)
Finally. This block is always run after the try and catch blocks. It does not matter whether an exception is triggered. And sometimes the finally runs, but the catch does not.
Java program that uses finally block public class Program { public static void main(String[] args) { String value = null; try { // This statement causes an exception because value is null. // ... Length() requires a non-null object. System.out.println(value.length()); } catch (Exception ex) { // This runs when the exception is thrown. System.out.println("Exception thrown!"); }
finally { // This statement is executed after the catch block. System.out.println("Finally done!"); } } } Output Exception thrown! Finally done!
Finally, no exceptions. This program throws no exception. But it still executes its finally block. The code in finally is always run after the try block is run.
Caution: Unless an exception may occur, this is not a worthwhile construct. In more complex programs, "finally" makes more sense.
Java program that uses finally without exception public class Program { public static void main(String[] args) { try { System.out.println("In try"); }
finally { // The finally is run even if no exception occurs. System.out.println("In finally"); } System.out.println("...Done"); } } Output In try In finally ...Done
StackOverflowError. Programs have a limited amount of stack memory. Recursion can sometimes overflow this memory—the program runs out of stack.StackOverflowError
Tip: In my experience, stack overflow is often caused by incorrect recursive calls.
Tip 2: A program, like the one here, can cause a StackOverflowError just by using unchecked recursion.
Recursion
Java program that encounters StackOverflowError public class Program { static void applyRecursion() { applyRecursion(); } public static void main(String[] args) { // Begin recursion.
applyRecursion (); } } Output Exception in thread "main" java.lang.StackOverflowError at program.Program.applyRecursion(Program.java:6) at program.Program.applyRecursion(Program.java:6) at program.Program.applyRecursion(Program.java:6)...
Benchmark, exception. Exception handling has a cost. For optimal performance, we should usually code defensively, preventing errors and not dealing with them at all.
Version 1: In this version of the code, we use an if-statement to prevent any exceptions from occurring.
Version 2: Here we just divide, and handle exceptions in a catch block if we cause an error.
Result: Checking for zero and preventing a division error is faster than handling errors in a try and catch clause.
Java program that benchmarks exceptions public class Program { public static void main(String[] args) { long t1 = System.currentTimeMillis(); // Version 1: check against zero before division. for (int i = 0; i < 1000000; i++) { int v = 0; for (int x = 0; x < 10; x++) {
if (x != 0) { v += 100 / x; } } if (v == 0) { System.out.println(v); } } long t2 = System.currentTimeMillis(); // Version 2: handle exceptions when divisor is zero. for (int i = 0; i < 1000000; i++) { int v = 0; for (int x = 0; x < 10; x++) {
try { v += 100 / x; }
catch (Exception ex) { // Errors are encountered. } } if (v == 0) { System.out.println(v); } } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 36 ms: if-check 89 ms: try, catch
ClassCastException. This error occurs when we try to cast a variable (often of type Object) to a class that is not valid. Classes in Java reside in a hierarchy: casts must traverse it.Casts, ClassCastException
NumberFormatException. This occurs when we try to parse a String that does not contain numeric characters. The operation is impossible. This is a common program speed issue.parseInt, NumberFormatException
Refactoring, null. Whenever an object may be null, we must check it against null before using it. If we omit this check, the program may cease operation. Using a null-check is a simple fix.
But: Other alternatives exist. We can use a special, "null object" instance that handles method calls with no errors.
Tip: The "null object" design pattern is described in the book Refactoring. It eliminates many branches in code.
Programs are complex. When an error occurs, dealing with it within the core control flow adds complexity. Instead we use exception-handling to isolate error conditions.
Related Links:
- Java Continue Keyword
- Java Convert Char Array to String
- Java Combine Arrays
- Java Console Examples
- Java Web Services Tutorial
- Java Odd and Even Numbers: Modulo Division
- Java IO
- Java 9 Features
- Java 8 Features
- Java String
- Java Regex | Regular Expression
- Java Filename With Date Example (Format String)
- Java Applet Tutorial
- Java Files.Copy: Copy File
- Java filter Example: findFirst, IntStream
- Java Final and final static Constants
- Java Super: Parent Class
- Java Date and Time
- Java do while loop
- Java Break
- Java Continue
- Java Comments
- Java Splitter Examples: split, splitToList
- Java Math.sqrt Method: java.lang.Math.sqrt
- Java Reflection
- Java Convert String to int
- JDBC Tutorial | What is Java Database Connectivity(JDBC)
- Java main() method
- Java HashMap Examples
- Java HashSet Examples
- Java Arrays.binarySearch
- Java Integer.bitCount and toBinaryString
- Java Overload Method Example
- Java First Words in String
- Java Convert ArrayList to String
- Java Convert boolean to int (Ternary Method)
- Java regionMatches Example and Performance
- Java ArrayDeque Examples
- Java ArrayList add and addAll (Insert Elements)
- Java ArrayList Clear
- Java ArrayList int, Integer Example
- Java ArrayList Examples
- Java Boolean Examples
- Java break Statement
- Java Newline Examples: System.lineSeparator
- Java Stream: Arrays.stream and ArrayList stream
- Java charAt Examples (String For Loop)
- Java Programs | Java Programming Examples
- Java OOPs Concepts
- Java Naming Conventions
- Java Constructor
- Java Class Example
- Java indexOf Examples
- Java Collections.addAll: Add Array to ArrayList
- Java Compound Interest
- Java Int Array
- Java Interface Examples
- Java 2D Array Examples
- Java Remove HTML Tags
- Java Stack Examples: java.util.Stack
- Java Enum Examples
- Java EnumMap Examples
- Java StackOverflowError
- Java startsWith and endsWith Methods
- Java Initialize ArrayList
- Java Object Array Examples: For, Cast and getClass
- Java Objects, Objects.requireNonNull Example
- Java Optional Examples
- Java Static Initializer
- Java static Keyword
- Java Package: Import Keyword Example
- Java Do While Loop Examples
- Java Double Numbers: Double.BYTES and Double.SIZE
- Java Truncate Number: Cast Double to Int
- Java Padding: Pad Left and Right of Strings
- Java Anagram Example: HashMap and ArrayList
- Java Math.abs: Absolute Value
- Java Extends: Class Inheritance
- Java String Class
- Java String Switch Example: Switch Versus HashMap
- Java StringBuffer: append, Performance
- Java Array Examples
- Java Remove Duplicates From ArrayList
- Java if, else if, else Statements
- Java Math.ceil Method
- Java This Keyword
- Java PriorityQueue Example (add, peek and poll)
- Java Process.start EXE: ProcessBuilder Examples
- Java Palindrome Method
- Java parseInt: Convert String to Int
- Java toCharArray: Convert String to Array
- Java Caesar Cipher
- Java Array Length: Get Size of Array
- Java String Array Examples
- Java String compareTo, compareToIgnoreCase
- Java String Concat: Append and Combine Strings
- Java Cast and Convert Types
- Java Math.floor Method, floorDiv and floorMod
- Java Math Class: java.lang.Math
- Java While Loop Examples
- Java Reverse String
- Java Download Web Pages: URL and openStream
- Java Math.pow Method
- Java Math.round Method
- Java Right String Part
- Java MongoDB Example
- Java Substring Examples, subSequence
- Java Prime Number Method
- Java Sum Methods: IntStream and reduce
- Java switch Examples
- Java Convert HashMap to ArrayList
- Java Remove Duplicate Chars
- Java Constructor: Overloaded, Default, This Constructors
- Java String isEmpty Method (Null, Empty Strings)
- Java Regex Examples (Pattern.matches)
- Java ROT13 Method
- Java Random Number Examples
- Java Recursion Example: Count Change
- Java reflect: getDeclaredMethod, invoke
- Java Count Letter Frequencies
- Java ImmutableList Examples
- Java String equals, equalsIgnoreCase and contentEquals
- Java valueOf and copyValueOf String Examples
- Java Vector Examples
- Java Word Count Methods: Split and For Loop
- Java Tutorial | Learn Java Programming
- Java toLowerCase, toUpperCase Examples
- Java Ternary Operator
- Java Tree: HashMap and Strings Example
- Java TreeMap Examples
- Java while loop
- Java Convert String to Byte Array
- Java Join Strings: String.join Method
- Java Modulo Operator Examples
- Java Integer.MAX VALUE, MIN and SIZE
- Java Lambda Expressions
- Java lastIndexOf Examples
- Java Multiple Return Values
- Java String.format Examples: Numbers and Strings
- Java Joiner Examples: join
- Java Keywords
- Java Replace Strings: replaceFirst and replaceAll
- Java return Examples
- Java Multithreading Interview Questions (2021)
- Java Collections Interview Questions (2021)
- Java Shuffle Arrays (Fisher Yates)
- Top 30 Java Design Patterns Interview Questions (2021)
- Java ListMultimap Examples
- Java String Occurrence Method: While Loop Method
- Java StringBuilder capacity
- Java Math.max and Math.min
- Java Factory Design Pattern
- Java StringBuilder Examples
- Java Mail Tutorial
- Java Swing Tutorial
- Java AWT Tutorial
- Java Fibonacci Sequence Examples
- Java StringTokenizer Example
- Java Method Examples: Instance and Static
- Java String Between, Before, After
- Java BitSet Examples
- Java System.gc, Runtime.getRuntime and freeMemory
- Java Character Examples
- Java Char Lookup Table
- Java BufferedWriter Examples: Write Strings to Text File
- Java Abstract Class
- Java Hashtable
- Java Math class with Methods
- Java Whitespace Methods
- Java Data Types
- Java Trim String Examples (Trim Start, End)
- Java Exceptions: try, catch and finally
- Java vs C#
- Java Float Numbers
- Java Truncate String
- Java Variables
- Java For Loop Examples
- Java Uppercase First Letter
- Java Inner Class
- Java Networking
- Java Keywords
- Java If else
- Java Switch
- Loops in Java | Java For Loop
- Java File: BufferedReader and FileReader
- Java Random Lowercase Letter
- Java Calendar Examples: Date and DateFormat
- Java Case Keyword
- Java Char Array
- Java ASCII Table
- Java IntStream.Range Example (Get Range of Numbers)
- Java length Example: Get Character Count
- Java Line Count for File
- Java Sort Examples: Arrays.sort, Comparable
- Java LinkedHashMap Example
- Java Split Examples
Related Links
Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf
bennetthatere1971.blogspot.com
Source: https://thedeveloperblog.com/java/try-java
0 Response to "Java Do While Try Catch Throw Exception Continue"
Post a Comment