More basic syntax - Loops and Exceptions
This week was one of those unproductive ones. I wasn't able to progress much in the bootcamp content, but I managed to cover the last theoretical units of this module:
Java, like most high-level languages derived from C, has three basic types of repetition loops (the famous loops): for, while and do-while.
For is used when we know in advance the size of the element that will be used as an iterable (like an array). This element may change dynamically (such as, for example, receiving data from an API), so you, as a developer, may not know exactly how many elements the iterable will have, but the code will know. Its basic structure is:
int[] numbers = {1, 2, 3, 4, 5}; for (int counter = 0; counter < numbers.length; counter++) { System.out.println(numbers[counter]); }The first part, the int counter = 0 is what we call the
count variable.
There must be prettier names, but this is one that explains what it does. She basically... does a count.
array numbers. This is what we call condition. As long as this condition is true (i.e. returns true), the loop will continue.
It does not necessarily need to be a comparison with some iterable, but it is normally used that way. And, finally, we have the
counter change, which can be an increment or a decrement. It is also not strictly necessary for this change to be made one by one, but it is the most common thing to see.
boolean podeJavascriptNoBack = false; while (!podeJavascriptNoBack) { System.out.println("Tá proibido JavaScript no back-end."); };What is between the parentheses in the loop declaration is the
condition that will be tested to check whether it continues or not. As long as the result of this condition is true, the action between the braces will be performed. This information is important because we can draw some conclusions from it:
- The
- loop action will only happen if the condition is positive. If in any given iteration the value of the condition changes (from true to false), the loop is interrupted and the action of that cycle is not executed; There may be some
- loop that does not perform any action because the condition was evaluated as false from the first iteration; If there is no action to change the result of the condition, we will find ourselves faced with an infinite
- loop.
before checking the condition. This means that the loop will perform at least one action before being interrupted. The syntax is very similar to while:
boolean condition = true; do { System.out.println("I'm inside a loop tee-hee!"); } while (condition);In the same way as while, if there is no action to change the result of the
condition, we will be dealing with an infinite loop.
To have even more control over the flow of the loops, there are still the break and continue keywords. break interrupts the entire loop, while continue interrupts only the current iteration. For example:
for (int i = 0; i <= 5; i++) { if (i == 4) break; System.out.println(i); //0 1 2 3 }In this example, for will run until counter i is greater than or equal to the number 5, and at each iteration the current counter will be printed on the console. However, when the counter is equal to 4, the loop will be interrupted and the last two numbers will not be printed.
Now, let's suppose you need to print the odd numbers from 1 to 10 in the console. We can use continue with the following structure:
for (int i = 0; i <= 10; i++) { if (i % 2 == 0) continue; System.out.println(i); //1 3 5 7 9 }That is, from 0 to 10, the
loop will check whether the counter is divisible by 2 using the modulo. If so, the loop will skip to the next iteration, but if not, the value of i will be printed in the terminal.
So far calm, right? Let's move on to exception handling.During the course of developing an application, problems will occur. In Java there is a distinction between serious problems, which affect the system or environment where the application is located (errors) and are normally unrecoverable conditions, and simpler problems, which the application manages to work around in some way (exceptions).
No caso dos errors, pode se tratar de algum problema físico (como um OutOfMemoryError), exaustão dos recursos disponíveis (como um StackOverflowError) ou até mesmo um erro da própria JVM (Internal Error). O importante notar é que, nesse caso, não tem como tratar isso. É uma situação que quebra a aplicação e normalmente a joga em um estado irrecuperável.
Mas existe uma categoria de problemas em que é possível se recuperar: as Exceptions. As exceções são problemas que podem ser capturados e devidamente tratados, para que nosso programa não quebre na cara do cliente. As exceções podem ter as mais variadas causas, que podem ser desde problemas com a infraestrutura (como leitura/escrita de dados, conexão com um banco de dados SQL etc) ou de lógica (como um erro de argumento inválido).
Para realizar o tratamento de erros, normalmente um bloco try-catch é utilizado. Essa estrutura tenta executar uma ação (descrita no bloco try) e, caso encontre alguma exceção, captura esse problema e realiza uma tratativa em cima dela (que está descrita no bloco catch). Ela segue essa sintaxe:
try { double result = 10 / 0; //isso vai lançar um ArithmeticException System.out.println(result); } catch (Exception e) { System.out.println("Não é possível dividir por 0, mané."); }
Podemos declarar vários blocos catch encadeados, para tentar granularizar as tratativas de acordo com os erros encontrados:
try { int result = 10 / 0; System.out.println(result); } catch (ArithmeticException e) { System.out.println("Não é possível dividir por 0, mané."); } catch (NullPointerException e) { System.out.println("Alguma coisa que você informou veio nula, bicho."); } catch (Exception e) { System.out.println("Deu ruim, irmão. Um erro genérico ocorreu: " + e.getMessage()); }
Além disso, ao final de toda a estrutura podemos declarar um bloco de código que sempre será executado, independente do caminho que o fluxo tomou: o finally:
try { int result = 10 / 0; System.out.println(result); } catch (ArithmeticException e) { System.out.println("Não é possível dividir por 0, mané."); } catch (NullPointerException e) { System.out.println("Alguma coisa que você informou veio nula, bicho."); } catch (Exception e) { System.out.println("Deu ruim, irmão. Um erro genérico ocorreu: " + e.getMessage()); } finally { System.out.println("Cabô."); }
Nesse exemplo, o código vai tentar dividir 10 por 0. Em seguida, vai entrar no primeiro bloco catch e imprimir "Não é possível dividir por 0, mané." e, por fim, entrar no bloco finally e imprimir "Cabô". Independente do caminho seguido, se houve sucesso ou não no try, o finally vai ser sempre executado.
Isso é tudo? Não! Nada é simples no Java.
As exceções podem ser divididas em dois tipos: as exceções verificadas (checked exceptions) e as não verificadas (unchecked exceptions). No caso das exceções verificadas, o compilador pede para que elas sejam tratadas para evitar que condições que estão além do escopo de código possam impactar no fluxo da aplicação. Por exemplo, o banco de dados que o programa está usando pode ter tido um problema, e a conexão pode falhar. Ao invés de simplesmente mostrar o erro, o Java pede que seja feita uma tratativa, como a abaixo:
public class DatabaseExample { public static void main(String[] args){ try { Connection conn = getConnection(); //executa alguma ação aqui... } catch (SQLException e) { System.out.println("Não foi possível conectar ao banco de dados. Erro: " + e.getMessage()); } } public static Connection getConnection() throws SQLExeption { String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "user"; String password = "mySuperSecretPassword"; //por favor não armazenem senhas no código //isso pode lançar um erro de SQL return DriverManager.getConnection(url, user, password); } }
O método getConnection() tenta realizar a conexão com o banco de dados usando as credenciais informadas, mas se em algum momento der problema (o banco está offline, as credenciais estão erradas, a máquina está desconectada da rede etc), a exceção será lançada. O método main, que chama o getConnection(), captura essa exceção e informa ao usuário que houve um erro ao realizar a conexão, ao invés se só mostrar a stack trace.
O compilador pede que esse tratamento seja implementado para proteger a aplicação de erros além do controle do desenvolvedor, tornando o programa mais resiliente e resistente à falhas.
Já as unchecked exceptions são exceções que não precisam ser obrigatoriamente tratadas. São casos de classes cujos métodos estão sob o controle do desenvolvedor e são, de modo geral, algum tipo de erro no código (seja de lógica ou uso incorreto de alguma API). Alguns exemplos desses são os famosos IllegalArgumentException, ArrayIndexOutOfBoundsException e NullPointerException.
Isso quer dizer que, se o compilador não reclamar, eu não preciso implementar um tratamento?
Não né. Muito melhor ter uma mensagem de erro amigável para o usuário saber o que tá acontecendo do que mandar isso aqui:
Bota tudo num try-catch que é sucesso.
E, por fim, teve um módulo sobre debugging usando Intellij e Eclipse, que foi mais prático do que teórico. Contudo, não consegui apresentar as informações passadas pela instrutura para o meio textual. Um post sobre debug em Java fica pro futuro.
Os dois módulos que restam nessa unidade são práticos (finalmente!). O próximo post vai ter bastante código. Até lá!
The above is the detailed content of More basic syntax - Loops and Exceptions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java uses wrapper classes because basic data types cannot directly participate in object-oriented operations, and object forms are often required in actual needs; 1. Collection classes can only store objects, such as Lists use automatic boxing to store numerical values; 2. Generics do not support basic types, and packaging classes must be used as type parameters; 3. Packaging classes can represent null values to distinguish unset or missing data; 4. Packaging classes provide practical methods such as string conversion to facilitate data parsing and processing, so in scenarios where these characteristics are needed, packaging classes are indispensable.

Enums in Java are special classes that represent fixed number of constant values. 1. Use the enum keyword definition; 2. Each enum value is a public static final instance of the enum type; 3. It can include fields, constructors and methods to add behavior to each constant; 4. It can be used in switch statements, supports direct comparison, and provides built-in methods such as name(), ordinal(), values() and valueOf(); 5. Enumeration can improve the type safety, readability and flexibility of the code, and is suitable for limited collection scenarios such as status codes, colors or week.

Java supports asynchronous programming including the use of CompletableFuture, responsive streams (such as ProjectReactor), and virtual threads in Java19. 1.CompletableFuture improves code readability and maintenance through chain calls, and supports task orchestration and exception handling; 2. ProjectReactor provides Mono and Flux types to implement responsive programming, with backpressure mechanism and rich operators; 3. Virtual threads reduce concurrency costs, are suitable for I/O-intensive tasks, and are lighter and easier to expand than traditional platform threads. Each method has applicable scenarios, and appropriate tools should be selected according to your needs and mixed models should be avoided to maintain simplicity

There are three main differences between Callable and Runnable in Java. First, the callable method can return the result, suitable for tasks that need to return values, such as Callable; while the run() method of Runnable has no return value, suitable for tasks that do not need to return, such as logging. Second, Callable allows to throw checked exceptions to facilitate error transmission; while Runnable must handle exceptions internally. Third, Runnable can be directly passed to Thread or ExecutorService, while Callable can only be submitted to ExecutorService and returns the Future object to

Interface Isolation Principle (ISP) requires that clients not rely on unused interfaces. The core is to replace large and complete interfaces with multiple small and refined interfaces. Violations of this principle include: an unimplemented exception was thrown when the class implements an interface, a large number of invalid methods are implemented, and irrelevant functions are forcibly classified into the same interface. Application methods include: dividing interfaces according to common methods, using split interfaces according to clients, and using combinations instead of multi-interface implementations if necessary. For example, split the Machine interfaces containing printing, scanning, and fax methods into Printer, Scanner, and FaxMachine. Rules can be relaxed appropriately when using all methods on small projects or all clients.

In Java, enums are suitable for representing fixed constant sets. Best practices include: 1. Use enum to represent fixed state or options to improve type safety and readability; 2. Add properties and methods to enums to enhance flexibility, such as defining fields, constructors, helper methods, etc.; 3. Use EnumMap and EnumSet to improve performance and type safety because they are more efficient based on arrays; 4. Avoid abuse of enums, such as dynamic values, frequent changes or complex logic scenarios, which should be replaced by other methods. Correct use of enum can improve code quality and reduce errors, but you need to pay attention to its applicable boundaries.

JavaNIO is a new IOAPI introduced by Java 1.4. 1) is aimed at buffers and channels, 2) contains Buffer, Channel and Selector core components, 3) supports non-blocking mode, and 4) handles concurrent connections more efficiently than traditional IO. Its advantages are reflected in: 1) Non-blocking IO reduces thread overhead, 2) Buffer improves data transmission efficiency, 3) Selector realizes multiplexing, and 4) Memory mapping speeds up file reading and writing. Note when using: 1) The flip/clear operation of the Buffer is easy to be confused, 2) Incomplete data needs to be processed manually without blocking, 3) Selector registration must be canceled in time, 4) NIO is not suitable for all scenarios.

Java's class loading mechanism is implemented through ClassLoader, and its core workflow is divided into three stages: loading, linking and initialization. During the loading phase, ClassLoader dynamically reads the bytecode of the class and creates Class objects; links include verifying the correctness of the class, allocating memory to static variables, and parsing symbol references; initialization performs static code blocks and static variable assignments. Class loading adopts the parent delegation model, and prioritizes the parent class loader to find classes, and try Bootstrap, Extension, and ApplicationClassLoader in turn to ensure that the core class library is safe and avoids duplicate loading. Developers can customize ClassLoader, such as URLClassL
