Home > Java > javaTutorial > body text

More basic syntax - Loops and Exceptions

WBOY
Release: 2024-08-21 06:21:07
Original
1032 people have browsed it

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:

Mais sintaxe básica - Loops e Exceções

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]);
}
Copy after login
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.

Mais sintaxe básica - Loops e Exceções

We initialize it to 0 and, in the second part, we compare it to the size of the

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.

The while loop on the other hand, does not provide for these finite amounts of iterations. It checks whether a condition is true and, if so, takes some action. Its structure is this:


boolean podeJavascriptNoBack = false;
while (!podeJavascriptNoBack) {
    System.out.println("Tá proibido JavaScript no back-end.");
};
Copy after login
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
  1. 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;
  2. There may be some
  3. loop that does not perform any action because the condition was evaluated as false from the first iteration;
  4. If there is no action to change the result of the condition, we will find ourselves faced with an infinite
  5. loop.
Do-while is very similar to while, with the difference that the action happens

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);
Copy after login
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
}
Copy after login
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
}
Copy after login
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é.");
}
Copy after login

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());  
}
Copy after login

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ô.");
}
Copy after login

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);
    }
}
Copy after login

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:

Mais sintaxe básica - Loops e Exceções

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!